Shawn Mclean Shawn Mclean - 25 days ago 9
ASP.NET (C#) Question

ASP.NET MVC HttpException message not shown on client

I'm building a RESTful web api with asp.net 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:

[HttpDelete]
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) {
alert("failed");
//response.responseText would contain the html you would see for asp.net
}


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

Answer

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

$.ajax({
    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
        alert(statusCode);
    }
});

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.