简体   繁体   English

HttpContent.ReadAsAsync 方法未从 Web API 调用返回正确的值

[英]HttpContent.ReadAsAsync method not returning correct value from a Web API call

My WebAPI method returns a status code as well as a boolean value:我的 WebAPI 方法返回一个状态代码以及一个布尔值:

[HttpPost]
public async Task<HttpResponseMessage> Register([FromBody]string parameter)
{
     HttpStatusCode statusCode = HttpStatusCode.OK;
     RegisterUserResult result = await _service.RegisterAsync(parameter);
     if (result == RegisterUserResult.AlreadyExists)
     {
          statusCode = HttpStatusCode.NoContent;
     }
     else if (result == RegisterUserResult.Created)
     {
          statusCode = HttpStatusCode.Created;
     }
     return Request.CreateResponse(statusCode, true);
}

On client side, I call HttpContent.ReadAsAsync method to check the boolean value in the response after making the API call:在客户端,我调用 HttpContent.ReadAsAsync 方法在进行 API 调用后检查响应中的布尔值:

HttpResponseMessage response = await client.PostAsJsonAsync(uri, parameter);
if (response.IsSuccessStatusCode)
{
     bool result = await response.Content.ReadAsAsync<bool>(); // result is false!
     return result;
}

The problem is that result returns as false .问题是结果返回为false What could I be missing?我可能会错过什么?

I realized that this happens because I am returning HttpStatusCode.Created for the initial action (user creation), however return HttpStatusCode.NoContent for subsequent actions on the same user.我意识到,这是因为我回国HttpStatusCode.Created初始动作(用户创造),但是返回HttpStatusCode.NoContent对同一用户的后续动作。

if (result == RegisterUserResult.AlreadyExists)
{
     statusCode = HttpStatusCode.NoContent;
}

While HttpStatusCode.NoContent is a successful status code, it will prevent providing a return value in Request.CreateResponse method by returning the default value of your intended return type.虽然 HttpStatusCode.NoContent 是一个成功的状态代码,但它会通过返回预期返回类型的默认值来阻止在Request.CreateResponse方法中提供返回值。 Meaning意义

Request.CreateResponse(statusCode, "True"); // returns null on client-side
Request.CreateResponse(statusCode, true); // returns false on client-side

Other success codes such as HttpStatusCode.OK or HttpStatusCode.Created will make sure that the intended value will be returned.其他成功代码(例如 HttpStatusCode.OK 或 HttpStatusCode.Created 将确保返回预期值。

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

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