Wednesday, August 27, 2014

throwing ASP.NET MVC Web API errors while also playing nicely with CORS

In an ASP.NET MVC Web API method one may typically throw an exception like so:

throw new Exception("No data was provided.");

 
 

...and then catch it at a jQuery .ajax implementation like so:

$.ajax({
   type: "POST",
   url: 'http://www.example.com/api/whatever',
   dataType: 'json',
   data: whatever,
   success: function (result) {
      alert("success: " + result);
   },
   error: function (request, status, error) {
      var responseText = JSON.parse(request.responseText);
      alert(responseText.ExceptionMessage);
   }
});

 
 

HOWEVER, if you are doing cross-site interactions and CORS is thrown into the mix, you cannot throw an error in this way and expect the specific error to make its way back to the jQuery implementation. Instead, try doing something like so in a method that returns an HttpResponseMessage anyways in the event of everything going well:

var error = Request.CreateResponse<string>(HttpStatusCode.BadRequest,
      "No data was provided.");
error.Headers.Add("Access-Control-Allow-Origin", "*");
return error;

 
 

The catching looks a bit different too:

$.ajax({
   type: "POST",
   url: 'http://www.example.com/api/whatever',
   dataType: 'json',
   data: whatever,
   success: function (result) {
      alert("success: " + result);
   },
   error: function (request, status, error) {
      alert(request.responseJSON);
   }
});

No comments:

Post a Comment