【问题标题】:Provide Fault Method in WCF receives FaultException with no details在 WCF 中提供故障方法接收到没有详细信息的 FaultException
【发布时间】:2019-02-12 14:42:32
【问题描述】:

我已经实现了一个IErrorHandler,因为我的服务女巫需要返回 403 而不是 o 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 字符串之后检查并不好,实际上它的授权不是身份验证......

【问题讨论】:

  • 哪里引发了异常?如果您可以找到或创建更合适的异常,您可以简单地检查它的类型。 if(error is NotAuthorizedException notAuthed){ // raise 403 error }
  • 据我所知,FailedAuthentication 代码是 SOAP 1.1 和 1.2 标准 wsse:FailedAuthentication

标签: c# wcf exception service microservices


【解决方案1】:

如果您使用的是 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. */
}

【讨论】:

  • 我的异常不包含任何关于状态码的信息。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-12-20
  • 1970-01-01
  • 2010-09-27
  • 1970-01-01
  • 2016-04-28
  • 2016-12-07
  • 1970-01-01
相关资源
最近更新 更多