加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 在WCF中提供故障方法接收到没有详细信息的FaultException

发布时间:2020-12-15 07:44:26 所属栏目:百科 来源:网络整理
导读:我为我的服务实现了一个IErrorHandler,如果授权错误,则需要返回403而不是400. 这就是我的ProvideFault方法的样子: public void ProvideFault(Exception error,MessageVersion version,ref Message fault){ if (((FaultException)error).Code.SubCode.Name =
我为我的服务实现了一个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,ref Message fault)
{
   /* your logic according to your needs. */
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读