Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 659
Markus Avatar asked Jan 10 '13 16:01

Markus


1 Answers

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.

like image 137
Rui Marques Avatar answered Sep 27 '22 17:09

Rui Marques