来自控制台应用程序的API POST调用

时间:2020-05-01 13:43:22

标签: c# asp.net-web-api webapi

如何从控制台应用程序执行REST API POST调用?

我想将类从控制台应用程序传递给REST API。如果必须执行GET调用而不是进行POST,则下面的代码有效。它正在击中API,但是在Parameter中它没有传递任何东西。

API

public class Student
{
    public int Id { get; set; }
    public string Name { get; set; }
}
public class ValuesController : ApiController
{
    // GET api/values
    public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2" };
    }

    // GET api/values/5
    public string Get(int id)
    {
        return "value";
    }

    // POST api/values

    //public void Post([FromBody]string value)
    //{

    //}
    public void Post([FromBody]Student value)
    {

    }



}

控制台应用程序

 static async Task CallWebAPIAsync()
    {

        var student = new Student() { Id = 1, Name = "Steve" };

        using (var client = new HttpClient())
        {
            //Send HTTP requests from here. 
            client.BaseAddress = new Uri("http://localhost:58847/");
              client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));


            HttpResponseMessage response = await client.PostAsJsonAsync("api/values", student);
            if (response.IsSuccessStatusCode)
            {

            }
            else
            {
                Console.WriteLine("Internal server Error");
            }
        }
    }

如果我从提琴手打来电话,那同样有效。

用户代理:提琴手 内容长度:31 主机:localhost:58847 内容类型:application / json

请求正文: { “ Id”:“ 1”, “名称”:“罗希特” }

3 个答案:

答案 0 :(得分:1)

这对我有用。

    public async Task CallWebAPIAsync()
    {
        var student  = "{'Id':'1','Name':'Steve'}";
        HttpClient client = new HttpClient();
        client.BaseAddress = new Uri("http://localhost:58847/");
        var response = await client.PostAsync("api/values", new StringContent(student, Encoding.UTF8, "application/json"));
        if (response != null)
        {
            Console.WriteLine(response.ToString());
        }
    }

答案 1 :(得分:0)

您没有序列化学生对象。 您可以尝试发送StringContent

StringContent sc = new StringContent(Student)

HttpResponseMessage response = await client.PostAsJsonAsync("api/values", sc);

如果这不起作用(我很长时间使用StringContent)。 使用NewtonSoft消毒器

string output = JsonConvert.SerializeObject(product);
HttpResponseMessage response = await client.PostAsJsonAsync("api/values", output);

答案 2 :(得分:0)

说实话,我不知道。看来您的StringContent并未将其灭菌为UTF8,您的静态API会默认尝试这样做。但是,默认情况下,您的控制台应用程序也应该这样做。

问题似乎是,静态API无法绑定字节数据,因此无法将数据分配给静态API中的类Student。

您可以尝试做的是在将帖子发布到API之前添加以下代码:

var encoding = System.Text.Encoding.Default;

它将告诉您默认的编码类型是什么。由于某种原因,UTF8可能不是默认编码。

相关问题