Post using HttpClient & Read HttpResponseMessage status

后端 未结 1 990
南方客
南方客 2021-01-22 00:44

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

相关标签:
1条回答
  • 2021-01-22 01:27

    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.

    0 讨论(0)
提交回复
热议问题