【发布时间】:2019-01-02 18:45:37
【问题描述】:
我已经创建了 Web API,我的问题是从它向客户端读取结果。
创建用户的WebApi方法:
[HttpPost]
public IActionResult PostNewUser([FromBody]UserDto userDto)
{
if (userDto == null)
return BadRequest(nameof(userDto));
IUsersService usersService = GetService<IUsersService>();
var id = usersService.Add(userDto);
return Created("api/users/", id.ToString());
}
而要调用API代码的客户端是:
public int CreateUser(UserDto dto)
{
using (HttpClient client = new HttpClient())
{
string endpoint = ApiQuery.BuildAddress(Endpoints.Users);
var json = new StringContent(JsonConvert.SerializeObject(dto), Encoding.UTF8, "application/json");
var postReult = client.PostAsync(endpoint, json).Result;
return 1; //??
}
}
它有效,响应给出 201 (Created) 但我不知道如何返回正确的结果,应该是:
/api/users/id_of_created_user
我在两个项目中都使用 netcore2.0
【问题讨论】:
-
当你有 postResult 时,你应该首先检查它的 IsSuccessStatusCode 属性,然后以一种或另一种方式读取内容(例如调用 ReadStreamAsync())。我还建议一直使用 async / await 避免在返回的任务上调用 Result。
-
你的意思是这样的?
var result = await postReult.Content.ReadAsStringAsync(); -
目前你在
var postReult收到了什么? -
问题是如果我得到 postRestul.Content.ReadAsAnything() 它不会给我 'api/users/newUserId' - 它只给我 newUserId
标签: c# asp.net-web-api asp.net-core asp.net-core-webapi