Is there a way to catch the HTTP 500 error returned by an .asmx web service from a .Net client?
Using .Net 4.5 (VS2015), the .Net client code consumes the .asmx web service and calls it using the code below:
var client = new WebserviceApi.MyServiceSoapClient();
var response = client.MyWebServiceMethod();
If the .asmx web service returns an HTTP 500 error with a SOAP message containing the error message details, the "response" variable is set to null.
Using Fiddler, the traffic shows the HTTP 500 response from the .asmx web service. The response contains a SOAP XML message with details on the error.
No exception is thrown or caught in the .Net client code, execution continues as normal.
This means there is no information for the client to pick up regarding the nature of the exception. All the client code can do is check if "response" is null, but the exception message is not available to the client code.
Is there any way to force the .Net client code to throw an exception if the .asmx web service returns an HTTP 500 response so that the error message can be checked/logged?
I had a similar problem for axis (java) web service. They were throwing exceptions that didn't appear on my side even though the response was really a HTTP 500.
I can't say for sure this will solve your case, but I solved mine overriding the GetWebResponse method and throwing the exception by myself when needed.
I did it by changing the web service client code generated by Visual Studio after adding Web Reference (generated file name is: Reference.cs, sometimes it's not visible in solution, you have to click 'Show All files' on top of the solution pane and then unfold your web service reference files.
internal class ChangedWebServiceClient : SomeSoapService
{
protected override WebResponse GetWebResponse(WebRequest request)
{
var response = base.GetWebResponse(request);
if (response != null)
{
var responseField = response.GetType().GetField("_base", BindingFlags.Instance | BindingFlags.NonPublic);
if (responseField != null)
{
var webResp = responseField.GetValue(response) as HttpWebResponse;
if (webResp != null)
{
if (webResp.StatusCode.Equals(HttpStatusCode.InternalServerError))
throw new WebException(
"HTTP 500 - Internal Server Error happened here. Or any other message that fits here well :)");
}
}
}
return response;
}
}
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