Can I set an HTTP response code and throw an exception in the ASMX JSON service?

In ASP.NET ASMX WebMethod that responds with JSON, can I get around the exception and set the HTTP response code? I thought that if I selected HttpException, the status code would be set accordingly, but it would not be able to force the service to respond with anything but a 500 error.

I 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 answers answer at 500.

Many thanks.

+7
source share
1 answer

Change the code as follows:

 [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 } } 

In principle, you cannot, that is, when throwing an exception, the result will always be 500.

+2
source

All Articles