In my WebAPI class, an ApiController
, I make a call such as:
string myCustomMessage = .....;
throw new HttpResponseException(
new HttpRespo
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.
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"}