I am developing a rest API on MVC3.
Whenever there is a problem with validation, I want to throw 500 + json that describes the error (the json can be the list of unvalidated fields).
The problem is that the json returns inside html that holds the entire HttpExeption
(Server Error in '/' Application.
)
If I put filterContext.ExceptionHandled = true;
the message goes out clean, but the client can't see the 500 error on his side.
This case: https://stackoverflow.com/a/4707762/936651 actually the html and gives clean json to the client, but also removes the 500 error.
Asked
Active
Viewed 3,016 times
1
-
Have you looked at the mvc 4 web api yet? If you were willing to change frameworks to that I think there is a built in way of doing what you describe. Plus a much easier way to build out an API. – Adam Schiavone Nov 25 '12 at 15:10
1 Answers
1
You could set the status code to 500 inside the custom error handler you have seen here
:
filterContext.RequestContext.HttpContext.Response.StatusCode = 500;
and on the client:
$.ajax({
url: '/home/foo',
success: function (result) {
alert('success');
},
error: function (jqXHR, textStatus, errorThrown) {
var json = $.parseJSON(jqXHR.responseText);
// TODO: do something with the json that was returned from the server
}
});

Community
- 1
- 1

Darin Dimitrov
- 1,023,142
- 271
- 3,287
- 2,928
-
I don't think you read or understood my entire post (-: you post me the link that I posted. please re-read that if you find some time, thanks mate! – SexyMF Nov 25 '12 at 18:06
-
Did you add the `filterContext.RequestContext.HttpContext.Response.StatusCode = 500;` line to the `MyErrorHandlerAttribute` shown in my previous post? What happened when you did so? In my previous post this line was missing so it is not surprising that the error handler was never hit on the AJAX request. So please read my answer carefully once again. – Darin Dimitrov Nov 25 '12 at 22:12