WCF - 错误处理取决于所使用的绑定

本文关键字:绑定 取决于 错误 处理 WCF | 更新日期: 2023-09-27 18:33:13

处理异常的方式上,在所使用的绑定方面是否有一些差异?

如果我使用 WSHttpBinding 或 BasicHttpBanding,我会得到不同的结果。

例如,这是我在客户端的错误处理例程:

//MyClient client = new MyClient("WSBinding");
MyClient client = new MyClient("BasicBinding");
try
{
    Result = client.DoTheWork("test");
    Console.WriteLine(Result);
}
catch (FaultException e)
{
    if (e.Code.SubCode.Name.Equals("BadParameters"))
        Console.WriteLine("Bad parameter entered");
    Console.WriteLine(e);
}

当我使用 WSHttpBinding 时,我可以在客户端上捕获异常,但是如果我使用 basicHttpHandling 我不能,我会得到:

Unhandled Exception: System.NullReferenceException: Object reference not set to
an instance of an object.

这是我的网络配置,

<system.serviceModel>
<bindings>
  <basicHttpBinding>
    <binding name="basicBinding">
      <security mode="TransportCredentialOnly">
        <transport clientCredentialType="Windows" />
      </security>
    </binding>
  </basicHttpBinding>   
  <wsHttpBinding>
    <binding name="wsBinding">
      <security mode="None">
        <transport clientCredentialType="None" />
        <message establishSecurityContext="false" />
      </security>
    </binding>
  </wsHttpBinding>
</bindings>
<services>
  <service name="MailboxServiceLibrary.MailboxService" behaviorConfiguration="ServiceBehavior" >
    <!--endpoint address="" binding="wsHttpBinding" bindingConfiguration="wsBinding" contract="ParServiceLibrary.IParService">
      <identity>
        <dns value="MyServer.com" />
      </identity>
    </endpoint-->     
    <endpoint address="" binding="basicHttpBinding" bindingConfiguration="basicBinding" contract="ParServiceLibrary.IParService"/>
    <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
  </service>
</services>
<behaviors>
  <serviceBehaviors>
    <behavior name="ServiceBehavior">
      <serviceMetadata httpGetEnabled="True"/>
      <serviceDebug includeExceptionDetailInFaults="True"/>
    </behavior>
  </serviceBehaviors>
</behaviors>

似乎BasicHttpBinding使用Soap 1.1格式,

对于WSHttpBinding,它使用Soap 1.2格式,但不确定这是否可能是原因。

谢谢

WCF - 错误处理取决于所使用的绑定

我刚刚意识到我使用了错误的方法在客户端站点中捕获异常,

我正在使用,

if (e.Code.SubCode.Name.Equals("MyFaultID"))

它一定是,

if (e.Code.Name.Equals("MyFaultID"))

这样在两个绑定中都可以正常工作。

对我来说看起来不对:

<security mode="TransportCredentialOnly"> 

它应该是"Transport","Message"或"TransportWithMessageCredential" - 不确定这是否导致了您的问题,但是您已经为basicHttpBinding添加了安全性,并为wsHttpBinding删除了它,所以不确定这最终是否是一个公平的测试?