在Silverlight 3之前如果WCF发生了异常,Silverlight将获取到“远程服务器返回了错误: NotFound。”的消息,无法获取到真实的异常,这为开发调试以及寻找错误带来了困扰。
但是Silverlight 3为我们带来了新的网络堆处理机制,从而使我们可以无缝地实现Silverlight端获取到WCF的真实异常信息。
原先对于下面这样一个WCF异常

Code
[ServiceContract(Namespace = "")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Service1
{
[OperationContract]
public int DoWork(int x, int y)
{
return x / y;
}
} 当Silverlight端捕获时就会出现Not Found的错误

Code
public MainPage()
{
InitializeComponent();
ServiceReference1.Service1Client client = new SilverlightApplication2.ServiceReference1.Service1Client();
client.DoWorkCompleted += new EventHandler<SilverlightApplication2.ServiceReference1.DoWorkCompletedEventArgs>(client_DoWorkCompleted);
client.DoWorkAsync(1, 0);
}
void client_DoWorkCompleted(object sender, SilverlightApplication2.ServiceReference1.DoWorkCompletedEventArgs e)
{
if (e.Error == null)
{
MessageBox.Show(e.Result.ToString());
}
else
{
MessageBox.Show(e.Error.Message);
}
} 现在我们只需要给WCF服务加上 [ServiceBehavior(IncludeExceptionDetailInFaults = true)] 这个Attribute,然后在客户端的初始化的地方加上

Code
bool registerResult = WebRequest.RegisterPrefix("http://", WebRequestCreator.ClientHttp);
bool httpsResult = WebRequest.RegisterPrefix("https://", WebRequestCreator.ClientHttp);
我习惯加在Application_Startup事件中,这样一加就可以正常获取到“试图除以零。 ”的错误了。
参考资料:
http://blogs.msdn.com/silverlight_sdk/archive/2009/08/12/new-networking-stack-in-silverlight-3.aspxhttp://blogs.msdn.com/carlosfigueira/archive/2009/08/15/fault-support-in-silverlight-3.aspxhttp://tomasz.janczuk.org/2009/07/pubsub-sample-using-http-polling-duplex.htmlhttp://blogs.msdn.com/silverlightws/http://code.msdn.microsoft.com/Project/Download/FileDownload.aspx?ProjectName=silverlightws&DownloadId=3473