HttpClient, Post 方法 POST 方法

时间:2021-05-26 20:15:11

标签: c# .net httprequest

尝试使用我的应用程序使用 httpClient 进行发布,我有这行代码

  public ActionResult Create(LutUsers users)
     {

     HttpResponseMessage response = client.PostAsync(client.BaseAddress + "/user/create", 
     **httpcontent**).Result;

     if (response.IsSuccessStatusCode)
        {

        }

    return View();
}

我的 httpcontent 应该是什么?我正在使用 web api 发布我的数据

感谢您的帮助

1 个答案:

答案 0 :(得分:0)

如果你可以使用异步方法,你可以像这样使用它:

HttpClient client = new HttpClient();
StringContent postContent = new StringContent("{ \"firstName\": \"John\" }");

var response = await client.PostAsync(client.BaseAddress + "/user/create", postContent);
var resString = await response.Content.ReadAsStringAsync();

如果你需要同步方法,你可以为它创建任务:

HttpClient client = new HttpClient();
StringContent postContent = new StringContent(content);

var task = Task.Run(() => client.PostAsync(client.BaseAddress + "/user/create", postContent)); 
task.Wait();
相关问题