简体   繁体   English

从WebApi接收IActionResult

[英]Receiving IActionResult from WebApi

I have created Web API, and my problem is reading results from it to client. 我创建了Web API,我的问题是从客户端读取结果。

WebApi method which creating user: 创建用户的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());
}

And the client which want to call API code is: 想要调用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; //?? 
    }
}

It works, response gives 201 (Created) but I have no idea how to return correct result, which should be: 它工作,响应给201(创建),但我不知道如何返回正确的结果,这应该是:

/api/users/id_of_created_user

I'm using netcore2.0 in both projects 我在两个项目中都使用netcore2.0

In the Web API either construct the created location URL manually 在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());
}

Or use one of the CreateAt* overloads 或者使用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());

In the client, the location is retrieved from the header of the response. 在客户端中,从响应的标头中检索位置。

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

You also appear to be sending the id as part of the response which can be retrieved from the response content. 您似乎也将响应的一部分作为响应的一部分发送,可以从响应内容中检索。

Note the refactoring of HttpClient to avoid creating an instance every time which can lead to socked exhaustion that can cause errors. 请注意HttpClient的重构,以避免每次都创建一个实例,这可能导致可能导致错误的socked耗尽。

Or you can always return JsonResult and return JSON object from the server with required data for the client. 或者,您始终可以返回JsonResult并从服务器返回JSON对象以及客户端所需的数据。 Here is an example to use 这是一个使用的例子

https://www.c-sharpcorner.com/UploadFile/2ed7ae/jsonresult-type-in-mvc/ https://www.c-sharpcorner.com/UploadFile/2ed7ae/jsonresult-type-in​​-mvc/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM