c# - WCF 中的 Provide Fault 方法接收没有详细信息的 FaultException

标签 c# wcf exception service 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.";
    }
}

我想知道是否有任何方法可以为错误及其状态代码编写更好的检查,或者如何获得授权异常而不是更通用的 FaultException 女巫?。我觉得在 FailedAuthentication 字符串之后检查不太好,事实上它的授权不是身份验证...

最佳答案

如果您使用的是 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";
   }
}

在你的情况下:

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. */
}

关于c# - WCF 中的 Provide Fault 方法接收没有详细信息的 FaultException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52219244/

相关文章:

c# - 从ChildVM中获取必要的ViewModel并将其设置为ParentVM中的属性

c# - EF Core 从多重数为零或一的模型中获取实体的导航属性

c# - 在代码隐藏中创建一个 ajaxToolkit TabPanel

作为 ASMX 公开的 WCF 服务不接受参数

WCF 和自定义 Soap 身份验证

java - FileNotFoundException 但文件存在于正确的路径中

java - 使用 throw 来处理用户定义的异常

c# - 使用同一程序集的不同版本

java.lang.ClassCastException : com. sun.mail.handlers.multipart_mixed 无法转换为 javax.activation.DataContentHandler

.net - 使用稍微复杂的方法引用 WCF 服务时获取 "Recursive collection data contract"