将WCF端的异常返回到Silverlight端有两种方法(不提示 远程服务not found,而是具体的错误)
第一种 在App.cs的构造里 bool bRegisterPrefix =WebRequest.RegisterPrefix(http://localhost:9999,WebRequestCreator.ClientHttp); 地址为服务的地址
public class SilverlightFaultBehavior : BehaviorExtensionElement,IEndpointBehavior
{
public void ApplydispatchBehavior(ServiceEndpoint endpoint,Endpointdispatcher endpointdispatcher)
{
SilverlightFaultMessageInspector inspector = new SilverlightFaultMessageInspector();
endpointdispatcher.dispatchRuntime.MessageInspectors.Add(inspector);
}
public class SilverlightFaultMessageInspector : IdispatchMessageInspector
{
public void BeforeSendReply(ref Message reply,object correlationState)
{
if (reply.IsFault)
{
HttpResponseMessageProperty property = new HttpResponseMessageproperty();
// Here the response code is changed to 200.
property.StatusCode = System.Net.HttpStatusCode.OK;
reply.Properties[HttpResponseMessageProperty.Name] = property;
}
}
public object AfterReceiveRequest(ref Message request,IClientChannel channel,InstanceContext instanceContext)
{
// Do nothing to the incoming message.
return null;
}
}// The following methods are stubs and not relevant.
public void AddBindingParameters(ServiceEndpoint endpoint,BindingParameterCollection bindingParameters){}public void ApplyClientBehavior(ServiceEndpoint endpoint,ClientRuntime clientRuntime){}public void Validate(ServiceEndpoint endpoint){}public override System.Type BehaviorType{get { return typeof(SilverlightFaultBehavior); }}protected override object CreateBehavior(){return new SilverlightFaultBehavior();}}
然后,在具体的服务类上加 [ServiceBehavior(IncludeExceptionDetailInFaults = true)] ,如
[ServiceBehavior(IncludeExceptionDetailInFaults = true)]
public class Service2 : IService2
{
public void DoWork()
{
throw new Exception("Customer error!");
}
}
<system.serviceModel>
<extensions>
<behaviorExtensions>
<add name="silverlightFaults" type="MyWcfServices.SilverlightFaultBehavior, MyWcfServices, Version=1.0.0.0, Culture=neutral,PublicKeyToken=null"/>
注意:type里,逗号加空格,不然报错 silverlightFaults未注册
</behaviorExtensions>
</extensions>
<behaviors>
<endpointBehaviors>
<behavior name="silverlightFaults">
<silverlightFaults />
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior >
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
</behaviors>
<bindings>
<basicHttpBinding>
<binding name="customBinding0">
<binaryMessageEncoding />
<httpTransport />
</binding>
</basicHttpBinding>
</bindings>
<services>
<service name="SoloWcfServices">
<endpoint address="" binding="customBinding"
behaviorConfiguration="silverlightFaults"
bindingConfiguration="customBinding0"
contract="SoloWcfServices" />
</service>
</services>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
</system.serviceModel>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。