Post using HttpClient & Read HttpResponseMessage status

隐身守侯 提交于 2019-12-20 03:18:18

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!