【问题标题】:How to post data or consume a web api using httpclient如何使用 httpclient 发布数据或使用 Web api
【发布时间】:2018-08-01 01:57:09
【问题描述】:

我想使用 httpclient 发布数据或使用 Web api。我对 asp.net 的了解是有限的,所以任何指向我正确方向的人都会有所帮助。 我有一个 url,我给它起了一个通用名称 localhost。我需要从这个 url 发布或使用服务。

这是我的代码示例:这是名为 Student 的模型类。

namespace Student.Models
{
    public class StudentInfo
    {
        public string id{ get; set; }
        public string firstname { get; set; }
        public string lastname { get; set; }
        public string subject { get; set; }
    }
}

这是名为 StudentController 的代码控制器:

public void Post([FromBody] string id, string firstname, string lastname, string subject)
{
    Student stu = new Student();
    stu.id = id;
    stu.firstname= firstname;
    stu.lastname = lastname;
    stu.subject = subject;

    var client = new HttpClient { BaseAddress = new Uri("https://localhost") };

    // call sync
    var response = client.PostAsync("/api/student/exist", 
    content).Result;
    if (response.IsSuccessStatusCode)
    {
    }
}

我在这一行得到错误内容不存在于当前上下文中:

// call sync
var response = client.PostAsync("/api/membership/exist", content).Result;

【问题讨论】:

    标签: asp.net asp.net-web-api


    【解决方案1】:

    你只是得到一个编译器错误,因为你试图使用一个变量,content,你没有在代码中的任何其他地方声明。我猜你犯了一个简单的错误,该行应该是:

    var response = client.PostAsync("/api/student/exist", stu).Result;

    【讨论】:

      【解决方案2】:

      为了发布 Student object 数据,我们需要在“发布请求”中传递它。因此,将content 替换为stu

      另外,请试试这个,为PostAsJsonAcync添加NuGet包Microsoft.AspNet.WebApi.Client并添加对System.Net.Http.Formatting的引用

      // call sync
      var response = client.PostAsJsonAsync("/api/student/exist", stu).Result;
      if (response.IsSuccessStatusCode)
      {
      }
      

      【讨论】:

        【解决方案3】:

        也不要阻止异步代码。让动作返回一个任务:

        public async Task Post([FromBody] string id, string firstname, string lastname, string subject)
        

        并将您的请求更改为:

        var response = await client.PostAsJsonAsync("/api/student/exist", stu);
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2011-09-01
          • 1970-01-01
          • 1970-01-01
          • 2018-08-10
          相关资源
          最近更新 更多