Capturing SOAP faults and handling exceptions - c#

I am consuming a web services. Some methods throw exception when i invoked, because the parameters are invalid values, for example. I want to handle the exceptions but it don't contains any data information, only the message "Bad Request". This is my http response:
try
{
var data = client.SomeMethod(4);
}
catch (Exception exception)
{
// exception.Message = Bad Request
// exception don't contains any more data information
}
How can I capture the other information

You can catch the exception with FaultException when the http status code is 2xx or 5xx, not 4xx. You can catch the http status code 4xx with System.ServiceModel.ProtocolException and then get the stream from the InnerException and parse it or get the FaultException from this stream. See http://blogs.msdn.com/b/nathana/archive/2011/03/31/deciphering-a-soap-fault-with-a-400-status-code.aspx for more details.

I'm assuming this is a WCF web service? You are catching to wide of an exception. Try with a FaultException<TDetail>.
Typical deployed services use the FaultContractAttribute to formally specify all SOAP faults that a client can expect to receive in the normal course of an operation. Error information in a FaultContractAttribute appears as a FaultException (where the typeparameter is the serializable error object specified in the operation's FaultContractAttribute) when it arrives at a client application. The FaultContractAttribute can be used to specify SOAP faults for both two-way service methods and for asynchronous method pairs.
Because FaultException is both a FaultException and therefore a CommunicationException, to catch specified SOAP faults make sure you catch the FaultException types prior to the FaultException and CommunicationException types or handle the specified exceptions in one of those exception handlers.

You can use try-catch like below. Then you can access other information. You have to find the "TDetail". It provides by the web service.
catch(FaultException<TDetail> ex)
{
ex.Code.ToString();
ex.Reason.ToString();
}
Other way.
FaultException faultException = (FaultException)ex;
MessageFault msgFault = faultException.CreateMessageFault();
XmlElement elm = msgFault.GetDetail<XmlElement>();

Related

How to catch "A potentially dangerous Request.Path value was detected from the client (:)" to avoid web role crash?

My MVC 5 web application running on Azure Cloud Service crashed with an unhandled exception "A potentially dangerous Request.Path value was detected from the client (:)".
The cause for this crash was some third party (maybe malicious) hit my endpoints with url:
http://myExampleHost.com/m:443/templates
The colon in the url cannot pass the path validation.
Some answers (A potentially dangerous Request.Path value was detected from the client (*)) suggest change the validate rules. However, out of security concerns, we may not want to compromise on this.
The ideal behavior for it that: we catch the exception, log it and return some error messages without crashing. How should we do that?
A more general question on this would be: how to catch an exception before the request hits controllers in MVC?
The ideal behavior for it that: we catch the exception, log it and return some error messages without crashing. How should we do that?
Per my understanding, you could leverage the Application_Error event to capture unhandled exception(s) within ASP.NET. Here is my test, you could refer to it:
protected void Application_Error()
{
HttpContext httpContext = HttpContext.Current;
var exception=Server.GetLastError();
var httpException = exception as HttpException ?? new HttpException(500, "Internal Server Error", exception);
var jsonResponse = new
{
Message = exception.Message,
StatusCode = httpException.GetHttpCode(),
StackTrace=httpException.StackTrace
};
httpContext.Response.ContentType = "application/json";
httpContext.Response.ContentEncoding = Encoding.UTF8;
httpContext.Response.Write(JsonConvert.SerializeObject(jsonResponse));
httpContext.Response.End();
}
Note: You could also redirect to a specific error page.
Moreover, you could leverage the customErrors in web.config and catch the error page for the specific HTTP error code. Also, you could check the HTTP status code under the Application_EndRequest event and write your custom response, details you could refer to this similar issue. Additionally, I would recommend you follow Demystifying ASP.NET MVC 5 Error Pages and Error Logging for more details about error handling.

Passing exception data between two applications

I don't know if this has been already answered or not. But, I am unable to find the example or cause of this problem.
Application 1:
try
{
//Read request and check for the request header element from the soap request
//validating request and salt
...here it might gets failed.
_requestValidationService.ValidateRequest();
}
catch (Exception ex)
{
ex.Data.Add("Exception", "test");
throw ex;
}
Application 2:
catch (Exception ex)
{
string aa = Convert.ToString(ex.Data["Exception"]);
throw ex;
}
I don't know what I am missing here. But aa seems to be always empty and ex.Data.Count is always zero.
I just want to pass one code between two applications without adding new class of an exception.
Note: These two applications are wcf calls.
[EDIT1]
Application 1 validate request is the IDispatchMessageInspector AfterReceiveRequest
Exceptions are not propagated to clients from a WCF service. Instead, a SOAP Fault (assuming you are using SOAP) will be sent to the client.
You can include exception details in the SOAP Fault, but in general it is not recommended to do so in production.
IMHO a better approach is to implement an IErrorHandler that provides the Fault with whatever data you want to send to the client, and also gives you the opportunity to log the exception server-side.
You can then catch FaultException on the client and have access to the data added by your custom error handler.
The exception class is designed by one throw / catch pair. If you should add any additional information to a cached exception, use the inner exception feature by the rethrow technique:
catch (Exception ex)
{
ErrorHandling.WriteError(ex);
var newEx = new MyException("Additional message", ex) // wrap the original exception instance.
newEx.Data.Add("Exception", "test");
throw newEx;
}
After catching the wrapper exception you can find the original exception in the InnerException property. Another advantage that the original and wrapper exceptions contain their own stack trace so it is easier to find location of error source.

Fiddler exception different than C# exception

We contact an Azure webservice to send over certain information.
When I send the request from C#, the exception provides the stacktrace from the sending side.
When I send the request from Fiddler, the exception provides the stacktrace from the receiving side.
I want to get the receiving side stacktrace in the logging as it's more usefull. Any ideas on how to do this? To my knowledge Fiddler uses HttpRequest as does C#
Code in C#:
HttpWebRequest r = (HttpWebRequest)WebRequest.Create(Adrewss);
...
HttpWebResponse response = (HttpWebResponse)r.GetResponse();
catch (Exception ex)
{
logEntry.Details = ex.ToString();
Let me know if more info is needed!
So C# ex =
500) Internal Server Error.
at System.Net.HttpWebRequest.GetResponse()
Fiddler ex:
{"Post":"System.NullReferenceException: Object reference not set to an instance of an object.\r\n at Test.Gateway.Models.Process.Transformer.GetTypeCode(String Type)\r\n etc
Fiddler doesn't use HTTPWebRequest at all, it talks to a raw socket. I'm guessing you're showing the raw text from the Response's body in Fiddler, while you're relying upon the exception (rather than the response body text) in your .NET code.

How do I get an HTTP status code from TTransport exceptions?

I'm using a thrift HttpClient (C#) to make web requests to a web server I've set up, and if that server returns something other than 200 (or 202 I imagine), my request throws a TTransport exception.
I'd like to respond to this exception based on the specific status code returned, but I don't see anything that exposes the status code in the exception's interface. Have I missed something? I know the exception message contains the status code, but I'd rather not have to parse that message to get at the status code.
If the server encounters an processing error, the recommended method is not throwing a HTTP 500. Instead, the server should signal this by means of an exception. Consider the following Thrift IDL:
exception MyProcessingError
{
1: string reason
2: string errorDetails
3: string recommendedAction
}
service FooBar {
void ProcessPayments( 1: double amount; 2: string receiver)
throws (1: MyProcessingError mpe)
}
Similar to args and struct fields, multiple exception types can be declared. The client can catch these exceptions as usual:
try
{
client.ProcessPayments( 47.11, "Dagobert");
}
catch (MyProcessingError e)
{
// process exception
}
Remarks
The server may only throw exceptions that are declared in the IDL for
the particular call.
Furthermore, oneway calls never return any value, thus no
exceptions either.

Catch Unauthorized exception

I am connecting to a webservice in my project by entereing user credentials(user name and password) i need to catch a unauthorized exception when the user enter invalid username/password. How can i do that
Are you attempting to catch an exception before calling the webservice?
try
{
result = Service.GetResult(param1, param2);
}
catch(System.Net.WebException ex)
{
Logger.WriteError("Error calling Webservice: ", ex.ToString());
}
WebException will catch server return codes as errors I believe, such as HTTP status 404: Not Found etc.
Is your web service SOAP? Are you using WCF on on the service side? If so, take a look at a Specifying and Handling Faults

Categories