我们正试图让我们的 WCF 服务返回带有 HTTP 200 响应代码的故障消息到我们的 Silverlight 4 客户端以下 this article on MSDN .在花了大部分时间在 SO 上进行配置、调试和搜索相关主题之后,我们仍然没有让它工作。
这是我们的 SilverlightFaultBehaviour 类:
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 Type BehaviorType
{
get { return typeof(SilverlightFaultBehavior); }
}
protected override object CreateBehavior()
{
return new SilverlightFaultBehavior();
}
}
这是我们 web.config 中的相关片段:
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="FooWebServiceBehaviour">
<serviceDebug includeExceptionDetailInFaults="true" />
<serviceMetadata httpGetEnabled="true" />
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="SilverlightFaultBehavior">
<silverlightFaults />
</behavior>
</endpointBehaviors>
</behaviors>
<services>
<service name="Foo.Web.Services.BarService" behaviorConfiguration="FooWebServiceBehaviour">
<endpoint address="" binding="customBinding"
bindingConfiguration="Foo.Web.Services.HttpBinding"
contract="Foo.Web.Service.IBarService"
behaviorConfiguration="SilverlightFaultBehavior" />
</service>
</services>
<extensions>
<behaviorExtensions>
<add name="silverlightFaults"
type="Foo.Web.Behavior.SilverlightFaultBehavior, Foo.WebBehavior, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
</behaviorExtensions>
</extensions>
</system.serviceModel>
问题似乎是从不调用 BeforeSendReply 方法,每次我们抛出 FaultException 时,我们的客户端仍然会收到有用的“未找到”错误。
是否有一些显而易见的事情是我们缺少让服务返回我们想要的响应代码?
最佳答案
结果证明这是我们的 web.config 中的一个错误,我们在我们的端点上用 basicHttpBinding 替换了生成的 customBinding,现在事情按预期工作。
奇怪的是,当添加“启用 Silverlight 的 WCF 服务”时,您会得到一个似乎不适用于 Silverlight 的默认配置。
关于wcf - 如何让 WCF 服务返回带有 HTTP 200 响应代码的错误消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5028765/