[英]Receiving IActionResult from WebApi
我創建了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(創建),但我不知道如何返回正確的結果,這應該是:
/api/users/id_of_created_user
我在兩個項目中都使用netcore2.0
在Web API中,手動構造創建的位置URL
[HttpPost]
public IActionResult PostNewUser([FromBody]UserDto userDto) {
if (userDto == null)
return BadRequest(nameof(userDto));
IUsersService usersService = GetService<IUsersService>();
var id = usersService.Add(userDto);
//construct desired URL
var url = string.Format("api/users/{0}",id.ToString());
return Created(url, id.ToString());
}
或者使用CreateAt*
重載之一
//return 201 created status code along with the
//controller, action, route values and the actual object that is created
return CreatedAtAction("ActionName", "ControllerName", new { id = id }, id.ToString());
//OR
//return 201 created status code along with the
//route name, route value, and the actual object that is created
return CreatedAtRoute("RouteName", new { id = id }, id.ToString());
在客戶端中,從響應的標頭中檢索位置。
status HttpClient client = new HttpClient();
public async Task<int> CreateUser(UserDto dto) {
string endpoint = ApiQuery.BuildAddress(Endpoints.Users);
var json = new StringContent(JsonConvert.SerializeObject(dto), Encoding.UTF8, "application/json");
var postResponse = await client.PostAsync(endpoint, json);
var location = postResponse.Headers.Location;// api/users/{id here}
var id = await postResponse.Content.ReadAsAsync<int>();
return id;
}
您似乎也將響應的一部分作為響應的一部分發送,可以從響應內容中檢索。
請注意HttpClient
的重構,以避免每次都創建一個實例,這可能導致可能導致錯誤的socked耗盡。
或者,您始終可以返回JsonResult並從服務器返回JSON對象以及客戶端所需的數據。 這是一個使用的例子
https://www.c-sharpcorner.com/UploadFile/2ed7ae/jsonresult-type-in-mvc/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.