gpt4 book ai didi

c# - 从 WebApi 接收 IActionResult

转载 作者:行者123 更新时间:2023-11-30 18:13:00 25 4
gpt4 key购买 nike

我已经创建了 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

最佳答案

在 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());

在客户端中,位置是从响应的 header 中检索的。

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;
}

您似乎也在发送 id 作为响应的一部分,可以从响应内容中检索它。

注意 HttpClient 的重构,以避免每次都创建一个实例,这可能导致 socked 耗尽,从而导致错误。

关于c# - 从 WebApi 接收 IActionResult,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54003949/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com