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

后端 未结 2 2023
粉色の甜心
粉色の甜心 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:15

    I use a response interceptor for that. A response interceptor is pretty much a "filter" where all responses pass through and I can ask about there status code and perform logic.

    Something like this:

    myModule.factory('responseInterceptor', function ($q) {
        return {
            response: function (res) {
               switch(res.status){
                 case 401:
                         // do what you want
               }
               return res;
            },
            responseError: function (res) {
                return $q.reject(res);
            }
        };
    });
    
    myModule.config(function ($httpProvider) {
        $httpProvider.interceptors.push('responseInterceptor');
    });
    

    About your custom message, you can add it in a http header. In my case, when I get a 401, I add a location header with a url and redirect to it.

    0 讨论(0)
  • 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"}
    
    0 讨论(0)
提交回复
热议问题