[英]Post using HttpClient & Read HttpResponseMessage status
I am posting to an API using HttpClient
and getting back the HttpResponseMessage
. 我正在使用
HttpClient
发布到API,并获取HttpResponseMessage
。 I am reading the status code from the reply but I it's always 200
我正在从回复中读取状态代码,但我总是
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
: 我从API回复
HttpResponseMessage
:
return new HttpResponseMessage(HttpStatusCode.Unauthorized);
But when I read the response
, it's always 200
但是当我阅读
response
,它总是200
How can I achieve this? 我该如何实现?
Asp.Net Core no longer recognizes HttpResponseMessage
as part of the pipeline. Asp.Net Core不再将
HttpResponseMessage
识别为管道的一部分。 This means it will be treated like any other returned model and serialized as content. 这意味着它将像其他返回的模型一样对待并序列化为内容。 Hence the 200 OK status.
因此为200 OK状态。
The API controller action should return IActionResult
derived result. API控制器操作应返回
IActionResult
派生的结果。
[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. 它是从
StatusCodeResult
派生的,并被用作简写形式来替换上面显示的代码。
Reference ControllerBase.Unauthorized . 参考ControllerBase.Unauthorized 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.