Shawn Mclean Shawn Mclean - 1 year ago 84
ASP.NET (C#) Question

ASP.NET MVC HttpException message not shown on client

I'm building a RESTful web api with mvc, which returns pure json data. On my client, I'm using backbone.js to communicate to it.

My question is, how do I capture the message in javascript? For eg. What if a user has no permission to delete or there was no item matching the id? I've been told to throw http errors instead of custom json.
So my code would be:

public ActionResult Index(int id)
if (id == 1)
throw new HttpException(404, "No user with that ID");
else if (id == 2)
throw new HttpException(401, "You have no authorization to delete this user");
return Json(true);

How do I access the message in my javascript callback? The callback would look like:

function (model, response) {
//response.responseText would contain the html you would see for

I do not see message i threw in the exception anywhere at all in the data that was returned from the server.

Answer Source

You should use the error callback on the client. The success callback is triggered only when the request succeeds:

    url: '/home/index',
    type: 'DELETE',
    data: { id: 1 },
    success: function (result) {
        alert('success'); // result will always be true here
    error: function (jqXHR, textStatus, errorThrown) {
        var statusCode = jqXHR.status; // will equal to 404

Now there is a caveat with 401 status code. When you throw 401 HTTP exception from the server, the forms authentication module intercepts it and automatically renders the LogIn page and replaces the 401 status code with 200. So the error handler will not be executed for this particular status code.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download