11

In an ASP.NET ASMX WebMethod that responds JSON, can i both throw an exception & set the HTTP response code? I thought if i threw an HttpException, the status code would be set appropriately, but it cannot get the service to respond with anything but a 500 error.

I have tried the following:

[WebMethod]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public void TestWebMethod() {
    throw new HttpException((int)HttpStatusCode.BadRequest, "Error Message");
}

Also:

[WebMethod]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public void TestWebMethod() {
    try {
        throw new HttpException((int)HttpStatusCode.BadRequest, "Error Message");
    }
    catch ( HttpException ex ) {
        Context.Response.StatusCode = ex.GetHttpCode();
        throw ex;
    }
}

These both respond with 500.

Many thanks.

Markus
  • 518
  • 6
  • 18

1 Answers1

4

Change your code to this:

[WebMethod]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public void TestWebMethod() {
    try {
        throw new HttpException((int)HttpStatusCode.BadRequest, "Error Message");
    }
    catch ( HttpException ex ) {
        Context.Response.StatusCode = ex.GetHttpCode();

        // See Markus comment
        // Context.Response.StatusDescription("Error Message");
        // Context.Response.StatusDescription(ex.Message); // exception message
        // Context.Response.StatusDescription(ex.ToString()); // full exception
    }
}

Basically you can't, that is, when throwing an exception the result will always be the same 500.

Rui Marques
  • 3,429
  • 1
  • 22
  • 26
  • This causes the reverse problem. The exception never makes it to the response. The client has the status code but not the error message. – Markus Jun 07 '13 at 12:40
  • Why not Response.StatusDescription(ex.ToString()) to have both? Just updated my answer. – Rui Marques Jun 07 '13 at 13:17
  • 1
    StatusDescription should mirror StatusCode (OK for 200, Not Found for 404, etc). It should not be a custom value. – Markus Jun 07 '13 at 16:39
  • @Markus, I agree but for a real 500 or any other not so common error a custom description could be useful. – Rui Marques Jun 11 '13 at 08:41