AngularJS $ http (...) errorHandler gets an empty string for data

I have a simple AngularJS $ http block like this:

$http(req).then(function successCallback(response) { alert(response); }, function errorCallback(response) { alert(response); }); 

My problem is that when my ASP.NET controller returns an HTTP error code, the JS errorCallback gets an object like:

 {data: "", status: 304, config: Object, statusText: "Not Modified"} 

No matter what I do, I cannot populate the data property in my callback.

If instead my controller returns the HTTP OK code, then the success callback is called and the return data is available. But not when it's a mistake ... help!

The controller function is the WebAPI POST handler and looks like this:

 [System.Web.Http.HttpPost] public async Task<HttpResponseMessage> Save([FromBody]object data) { ...<snip>... return new HttpResponseMessage { StatusCode = HttpStatusCode.NotModified, Content = new JsonContent(JObject.FromObject(new { success = false, message = "User not authorised to perform this action." })) }; } 

Same design, but with?

 StatusCode = HttpStatusCode.OK 

Successfully retrieved in the success callback in JS.

+5
source share
1 answer

So, after considering the comments on my question, it turns out that the problem was caused by my choice of Http status codes. I came back

 StatusCode = HttpStatusCode.NotModified, 

This code has special meaning, and it seems that the "data" blob is intentionally devoid.

Instead, if I use code like

 StatusCode = HttpStatusCode.Unauthorized, 

The 'data' block is populated, as expected, in the Angular callback.

This example returns the expected error data;

 [System.Web.Http.HttpPost] public async Task<HttpResponseMessage> Save([FromBody]object data) { ...<snip>... return new HttpResponseMessage { StatusCode = HttpStatusCode.Unauthorized, Content = new JsonContent(JObject.FromObject(new { success = false, message = "User not authorised to perform this action." })) }; } 
+2
source

All Articles