0

I'm sure this is simple but ... how are you meant to raise a HTTP 500 within a web service which returns a IHttpActionResult.

I can return a System.Web.Http.Results.Ok and end up with 200 client side but I can't find how to return anything other than a 200.

I've tried

   HttpStatusCodeResult r = new HttpStatusCodeResult(HttpStatusCode.InternalServerError, "BOO");

which is the right idea but I can't work out how to cast a HttpStatusCodeResult to IHttpStatusCodeResult.

I've also tried changing the return type to HttpStatusCodeResult (so I can use the above) but when I do that the jQuery on the client sees the result as a 'success' (even though with the Javascript you can see 'StatusCode' as 500 and the 'StatusDescription' as 'BOO'.

All I really want to do is :

  • be free to return any HTTP return value
  • include a message with it
  • have jQuery recognise that some HTTP returns should be handled by .done and others by .fail

Thanks.

glaucon
  • 8,112
  • 9
  • 41
  • 63

1 Answers1

0

OK well I believe I have found a way to do this. The answer is in this SO question here : https://stackoverflow.com/a/11328266 .

First you change the method return to HttpResponseMessage .

Then when you wish to signal an error you execute :

return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "BIG PROBLEM");

Back on the client I have code which looks like this :

promise.done(function(data, textStatus, jqXHR) {
                console.log(".done for within updateButtonClickHandler");
            })
promise.fail(function(data, textStatus, jqXHR) {
                console.log(".fail for within updateButtonClickHandler");
            })
promise.always(function(data, textStatus, jqXHR) {
                console.log(".always for within updateButtonClickHandler");

And the result of executing CreateErrorResponse is that the promise.fail executes in the client-side code.

Within that javascript function data.responseJSON.Message holds the message passed as the second argument in the C# code (in my example "BIG PROBLEM") and data.status holds 500 (corresponding to the HttpStatusCode.InternalServerError).

You can adapt this to generate any HTTP code you wish to return by using different HttpResponseMessage values (of which there are quite a few).

Community
  • 1
  • 1
glaucon
  • 8,112
  • 9
  • 41
  • 63