Can I Set the HTTP Response Code & Throw an Exception on an ASMX JSON Service?
Asked Answered
K

1

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.

Kegler answered 10/1, 2013 at 16:16 Comment(1)
Did you get anywhere with this?Dyson
N
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.

Noontide answered 7/6, 2013 at 8:56 Comment(4)
This causes the reverse problem. The exception never makes it to the response. The client has the status code but not the error message.Kegler
Why not Response.StatusDescription(ex.ToString()) to have both? Just updated my answer.Noontide
StatusDescription should mirror StatusCode (OK for 200, Not Found for 404, etc). It should not be a custom value.Kegler
@Markus, I agree but for a real 500 or any other not so common error a custom description could be useful.Noontide

© 2022 - 2024 — McMap. All rights reserved.