這裏是爲別人attemping這
首先一個的IDispatchMessageInspector
public class CustomResponseFormatterMessageInspector : IDispatchMessageInspector
{
public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
{
return null;
}
public void BeforeSendReply(ref Message reply, object correlationState)
{
var prop = (HttpResponseMessageProperty)reply.Properties[HttpResponseMessageProperty.Name];
if (prop.StatusCode == HttpStatusCode.NotFound)
{
ErrorResponse(ref reply);
}
}
private void ErrorResponse(ref Message original)
{
const string ERROR_HTML = @"<html><HEAD><TITLE>Request Error</TITLE></HEAD><BODY> <H1>My Error processing request {1}</H1><P>{0}</P></BODY></html>";
XElement response = XElement.Load(new StringReader(string.Format(ERROR_HTML, "A Resource does not exsist at this location.", HttpStatusCode.NotFound)));
Message reply = Message.CreateMessage(original.Version, null, response);
reply.Headers.CopyHeadersFrom(original);
reply.Properties.CopyProperties(original.Properties);
original = reply;
}
}
實例的相關代碼snipets然後注入IServiceBehaviour
這個我加
ed.DispatchRuntime.MessageInspectors.Add(new CustomResponseFormatterMessageInspector());
有可能在這個與我的實現有關的其他代碼,但這是我所添加的。
public class DependencyInjectionServiceBehavior : IServiceBehavior
{
public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
{
foreach (ChannelDispatcherBase cdb in serviceHostBase.ChannelDispatchers)
{
var cd = cdb as ChannelDispatcher;
if (cd != null)
{
foreach (EndpointDispatcher ed in cd.Endpoints)
{
ed.DispatchRuntime.InstanceProvider =
new DependencyInjectionInstanceProvider(serviceDescription.ServiceType);
ed.DispatchRuntime.MessageInspectors.Add(new CustomResponseFormatterMessageInspector());
}
}
}
}
public void AddBindingParameters(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase, Collection<ServiceEndpoint> endpoints, BindingParameterCollection bindingParameters)
{
}
public void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
{
}
}
嘿,這工作得很好! – Bluephlame 2010-10-04 05:14:41