How do you return status 401 from WebAPI to AngularJS and also include a custom message?

后端 未结 2 2037
粉色の甜心
粉色の甜心 2020-12-20 13:56

In my WebAPI class, an ApiController, I make a call such as:

string myCustomMessage = .....;

throw new HttpResponseException(
    new HttpRespo         


        
2条回答
  •  无人及你
    2020-12-20 14:21

    Try returning HttpResponseMessage like this.

    public HttpResponseMessage Get()
    {
        return Request.CreateErrorResponse(
                  HttpStatusCode.Unauthorized, "You are not authorized");
    }
    

    This should produce an HTTP response message like this.

    HTTP/1.1 401 Unauthorized
    Content-Type: application/json; charset=utf-8
    Server: Microsoft-IIS/8.0
    Date: Sat, 12 Apr 2014 07:12:54 GMT
    Content-Length: 36
    
    {"Message":"You are not authorized"}
    

提交回复
热议问题