本文介绍了使用HttpClient&发布读取HttpResponseMessage状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用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.

参考 ControllerBase.未经授权.

这篇关于使用HttpClient&发布读取HttpResponseMessage状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-22 20:06