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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With