在WCF中提供Fault方法接收FaultException而没有详细信息

Ras*_*dan 7 c# service wcf exception microservices

我已经IErrorHandler为我的服务实施了一个女巫需要返回403而不是400以防错误授权.
这是我的ProvideFault方法的样子:

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.";
    }
}
Run Code Online (Sandbox Code Playgroud)

我想知道是否有任何方法可以为错误及其状态代码编写更好的检查,或者如何获得授权异常而不是FaultException女巫更普遍?我发现在FailedAuthentication字符串后检查并不好,事实上它的授权不是认证...

Bar*_*r J 4

如果您使用的是 C# 6.0 及更高版本,则可以使用Exception Filters。例子是:

public string Example() 
{
   try
   {
      /* Method Logic */
      return string.Empty;
   }
   catch (System.Net.Http.HttpRequestException e) when (e.Message.Contains("400"))
   {
      return "unauthorized";
   }
}
Run Code Online (Sandbox Code Playgroud)

在你的情况下:

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. */
}
Run Code Online (Sandbox Code Playgroud)