问题描述
我正在使用HttpClient
发布到API,然后取回HttpResponseMessage
.我正在从回复中读取状态代码,但始终为200
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
发布:
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);
我正在从API回复HttpResponseMessage
:
return new HttpResponseMessage(HttpStatusCode.Unauthorized);
但是当我阅读response
时,它总是200
But when I read the response
, it's always 200
我该如何实现?
推荐答案
Asp.Net Core不再将HttpResponseMessage
识别为管道的一部分.这意味着它将像其他返回的模型一样对待,并序列化为内容.因此状态为200 OK.
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.
API控制器操作应返回IActionResult
派生的结果.
The API controller action should return IActionResult
derived result.
[HttpPost]
public IActionResult SomeAction(...) {
//...
return StatusCode((int)HttpStatusCode.Unauthorized); //401
//...
}
或者只是使用
return Unauthorized();
从StatusCodeResult
衍生而来的
,可以用快捷方式替换上面显示的代码.
which is derived from StatusCodeResult
and is used a short hand to replace the code shown above.
这篇关于使用HttpClient&发布读取HttpResponseMessage状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!