从WebApi接收IActionResult

时间:2019-01-02 09:30:14

标签: c# asp.net-web-api asp.net-core asp.net-core-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

2 个答案:

答案 0 :(得分: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;
}

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

请注意,HttpClient的重构可避免每次都创建一个实例,而该实例可能会导致精疲力尽,进而导致错误。

答案 1 :(得分:0)

或者,您始终可以返回JsonResult并从服务器返回JSON对象,其中包含客户端所需的数据。这是一个使用示例

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