Reputation: 71
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...
Upvotes: 7
Views: 271
Reputation: 10927
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. */
}
Upvotes: 4