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


73

如何在不使用App.Config的情况下在代码中设置IncludeExceptionDetailInFaults?

Answers:


108

是的,可以确定-在打开服务主机之前,在服务器端。但是,这将要求您自托管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文件中引用此自定义服务主机工厂。


3
在本地命名管道WCF应用程序与运行服务上节省了我的生命。谢谢 !
拉里

34

您也可以在继承接口的类声明上方的[ServiceBehavior]标签中进行设置

[ServiceBehavior(IncludeExceptionDetailInFaults = true)]
public class MyClass:IMyService
{
...
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.