如何使用httpclient

时间:2018-08-01 01:57:09

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

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

这是我的代码示例:这是名为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;

3 个答案:

答案 0 :(得分:0)

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

此外,请尝试此操作,为Microsoft.AspNet.WebApi.Client添加NuGet软件包PostAsJsonAcync并添加对System.Net.Http.Formatting的引用

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

答案 1 :(得分:0)

由于尝试使用变量content(您未在代码中的其他位置声明变量)而导致编译器错误。我猜测您犯了一个简单的错误,该行应显示为:

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

答案 2 :(得分:0)

也不要阻止异步代码。使操作返回任务:

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

并将您的请求更改为:

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