简体   繁体   中英

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:

[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:

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 . 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.

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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