WCF - Send exception from server side to client

异常信息如:

The server was unable to process the request due to an internal error. For more information about the error, either turn on IncludeExceptionDetailInFaults (either from ServiceBehaviorAttribute or from the configuration behavior) on the server in order to send the exception information back to the client, or turn on tracing as per the Microsoft .NET Framework SDK documentation and inspect the server trace logs.

解决方法有两种方式:

  • 编程方式
ServiceDebugBehavior debug = host.Description.Behaviors.Find();
 
// if not found - add behavior with setting turned on 

if (debug == null) {
    host.Description.Behaviors.Add(new ServiceDebugBehavior() { IncludeExceptionDetailInFaults = true });
}
else {
    // make sure setting is turned ON

    if (!debug.IncludeExceptionDetailInFaults) {
        debug.IncludeExceptionDetailInFaults = true;
    }
}
  • 配置方式

首先在.config中定义一个Behavior

<configuration>
  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior name="debug">
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
    ...
  </system.serviceModel>
</configuration>

然后在service中应用这个Behavior

<configuration>
  <system.serviceModel>
    ...
    <services>
      <service name="MyServiceName" behaviorConfiguration="debug" />
    </services>
  </system.serviceModel>
</configuration>