I have implemented an IErrorHandler
for my service witch needs to return 403 instead o 400 in case of wrong Authorization.
This is how my ProvideFault
method looks like:
public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
{
if (((FaultException)error).Code.SubCode.Name == "FailedAuthentication")
{
WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.Forbidden;
WebOperationContext.Current.OutgoingResponse.StatusDescription =
"StatusCode is forced to change in order to have the correct response on authentication.";
}
}
I wonder if there is any way to write a more nicer check for the error and its status code, or how to get an authorization exception not a FaultException
witch is more general?. I don't find it nice to check after the FailedAuthentication
string, and in fact its authorization not authentication...
In a WCF service, if it throws an exception inside the service, the client will not get the details. In order to get the formatted exception details on client side, you need to use FaultException instead to let the client know the details. The FaultException information can be serialized as expected.
What is fault Contract? A Fault Contract is a way to handle an error/exception in WCF. In C# we can handle the error using try and catch blocks at the client-side. The purpose of a Fault Contract is to handle an error by the service class and display in the client-side.
In a service, use the FaultException class to create an untyped fault to return to the client for debugging purposes. In a client, catch FaultException objects to handle unknown or generic faults, such as those returned by a service with the IncludeExceptionDetailInFaults property set to true .
If your are using C# 6.0 and above, you can use Exception Filters. The example is:
public string Example()
{
try
{
/* Method Logic */
return string.Empty;
}
catch (System.Net.Http.HttpRequestException e) when (e.Message.Contains("400"))
{
return "unauthorized";
}
}
In your case:
public string Example()
{
try
{
/* Method Logic */
return string.Empty;
}
catch (System.Net.Http.HttpRequestException e) when (e.Message.Contains("400"))
{
ProvideFault(e, "", e.Message);
}
}
public void ProvideFault(System.Net.Http.HttpRequestException error, MessageVersion version, ref Message fault)
{
/* your logic according to your needs. */
}
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