问题
I am posting to an API using HttpClient
and getting back the HttpResponseMessage
.
I am reading the status code from the reply but I it's always 200
Posting:
var json = JsonConvert.SerializeObject(loginDto);
var stringContent = new StringContent(json, Encoding.UTF8, "application/json");
var client = new HttpClient();
var response = await client.PostAsync("http://localhost:57770/api/Account/Login", stringContent);
I am replying from API the HttpResponseMessage
:
return new HttpResponseMessage(HttpStatusCode.Unauthorized);
But when I read the response
, it's always 200
How can I achieve this?
回答1:
Asp.Net Core no longer recognizes HttpResponseMessage
as part of the pipeline. This means it will be treated like any other returned model and serialized as content. Hence the 200 OK status.
The API controller action should return IActionResult
derived result.
[HttpPost]
public IActionResult SomeAction(...) {
//...
return StatusCode((int)HttpStatusCode.Unauthorized); //401
//...
}
Or just use
return Unauthorized();
which is derived from StatusCodeResult
and is used a short hand to replace the code shown above.
Reference ControllerBase.Unauthorized.
来源:https://stackoverflow.com/questions/52916397/post-using-httpclient-read-httpresponsemessage-status