【问题标题】:Receiving IActionResult from WebApi从 WebApi 接收 IActionResult
【发布时间】: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


【解决方案1】:

在 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 作为响应的一部分发送,可以从响应内容中检索到。

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

【讨论】:

    【解决方案2】:

    或者您总是可以返回 JsonResult 并从服务器返回 JSON 对象以及客户端所需的数据。这是一个使用示例

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-02-12
      • 2015-10-26
      • 1970-01-01
      • 2017-10-11
      • 1970-01-01
      • 2019-08-08
      • 2019-01-16
      相关资源
      最近更新 更多