在 WCF 的代码中将 IncludeExceptionDetailInFaults 设置为 true

如何在代码中设置 IncludeExceptionDetailInFaults 而不使用 App.Config?

51792 次浏览

是的,当然-在服务器端,在您打开服务主机之前。然而,这需要您自己托管 WCF 服务-不会在 IIS 托管场景中工作:

ServiceHost host = new ServiceHost(typeof(MyWCFService));


ServiceDebugBehavior debug = host.Description.Behaviors.Find<ServiceDebugBehavior>();


// 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;
}
}


host.Open();

如果您需要在 IIS 宿主中做同样的事情,那么您必须创建自己的定制 MyServiceHost后代和一个合适的 MyServiceHostFactory来实例化这样一个定制服务宿主,并在您的 * 中引用这个定制服务宿主工厂。Svc 文件。

您还可以在继承接口的类声明上面的[ ServiceBehavior ]标记中设置它

[ServiceBehavior(IncludeExceptionDetailInFaults = true)]
public class MyClass:IMyService
{
...
}