微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – 我应该将所有WCF服务代码包装在try catch块中吗?

try
{
    ///// here is the code that might throw erros. If I discover the user is unauthorized I throw a WebFaultException myself to alert the client
}      
catch (WebFaultException ex)
{
    throw ex; //but if I wrap all code in try-catch,I have to rethrow the exception o the status code reaches the client
}
catch (Exception ex)
{
    throw new WebFaultException(ex.Message,HttpStatusCode.InternalServerError);
}

我应该把所有东西都包在试试中吗,或者你推荐什么?我使用WCF和rest-ful JSON服务

解决方法

你可以做到,但最好将 IErrorHandleradd it as a behaviour实现到你的服务,这将允许你在一个地方处理未处理的异常,这样你就可以在那里创建一个故障异常,将细节返回到用户.
ErrorHandler : IErrorHandler
{
... just implement the handling of errors here,however you want to handle them
}

然后创建一个使用它的行为:

/// <summary>
///   Custom WCF BehavIoUr for Service Level Exception handling.
/// </summary>
public class ErrorHandlerBehavior : IServiceBehavior
    {
    #region Implementation of IServiceBehavior


    public void Validate (ServiceDescription serviceDescription,ServiceHostBase serviceHostBase)
        {
        }


    public void AddBindingParameters (ServiceDescription serviceDescription,ServiceHostBase serviceHostBase,Collection<ServiceEndpoint> endpoints,BindingParameterCollection bindingParameters)
        {
        }


    public void ApplydispatchBehavior (ServiceDescription serviceDescription,ServiceHostBase serviceHostBase)
        {
        IErrorHandler errorHandler = new ErrorHandler ();

        foreach (ChanneldispatcherBase channeldispatcherBase in serviceHostBase.Channeldispatchers)
            {
            var channeldispatcher = channeldispatcherBase as Channeldispatcher;

            if (channeldispatcher != null)
                {
                channeldispatcher.ErrorHandlers.Add (errorHandler);
                }
            }
        }

    #endregion
    }

然后,如果您是自托管,您只需以编程方式添加行为:

myServiceHost.Description.Behaviors.Add (new ErrorHandlerBehavior ());

如果你想通过配置添加它,那么你需要其中一个

public class ErrorHandlerElement : BehaviorExtensionElement
    {
    public override Type BehaviorType
        {
        get { return typeof (ErrorHandlerBehavior); }
        }

    protected override object CreateBehavior ()
        {
        return new ErrorHandlerBehavior ();
        }
    }
}

然后是配置:

<system.serviceModel>
<extensions>
  <behaviorExtensions>
    <add name="ErrorLogging" type="ErrorHandlerBehavior,ErrorHandling,Version=1.0.0.0,Culture=neutral,PublicKeyToken=<whatever>" />
  </behaviorExtensions>
</extensions>
<bindings>
  <basicHttpBinding>
    <binding name="basicBinding">
    </binding>
  </basicHttpBinding>
</bindings>
<services>
  <service behaviorConfiguration="Service1Behavior" name="Service">
    <endpoint address="" binding="basicHttpBinding"  bindingConfiguration="basicBinding" contract="Service" />
  </service>
</services>
<behaviors>
  <serviceBehaviors>
    <behavior name="Service1Behavior">
      <serviceMetadata httpGetUrl="" httpGetEnabled="true" />
      <serviceDebug includeExceptionDetailInFaults="false" />
      <ErrorLogging />  <--this adds the behavIoUr to the service behavIoUrs -->
    </behavior>
  </serviceBehaviors>
</behaviors>

原文地址:https://www.jb51.cc/csharp/98597.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐