使用与WCF休息DataContractSurrogateWCF、DataContractSurrogate

由网友(青稚)分享简介:我如何使用DataContractSurrogate我的WCF REST服务(使用WebServiceHostFactory托管)?How can I use a DataContractSurrogate for my WCF REST service (hosted using a WebServiceHostF...

我如何使用DataContractSurrogate我的WCF REST服务(使用WebServiceHostFactory托管)?

How can I use a DataContractSurrogate for my WCF REST service (hosted using a WebServiceHostFactory)?

我不认为增加一个的方式,即使我添加自定义IOperationBehavior,该WebServiceHost自动覆盖并忽略它。

I don't see a way of adding one and even if I add a custom IOperationBehavior, the WebServiceHost automatically overwrites and ignores it.

推荐答案

我设法得到它的工作:在IIS中使用WebServiceHostFactory WCF 4.0 REST服务托管

I managed to get it working: WCF 4.0 REST service hosted using a WebServiceHostFactory in IIS.

我用了一个自定义属性注入我NHProxyDataContractSurrogate:

I used a custom attribute to inject my NHProxyDataContractSurrogate:

public class CanSerializeNHProxyAttribute : Attribute, IContractBehavior
{
    public void ApplyClientBehavior(ContractDescription description, ServiceEndpoint endpoint, System.ServiceModel.Dispatcher.ClientRuntime proxy)
    {
        foreach (OperationDescription opDesc in description.Operations)
        {
            ApplyDataContractSurrogate(opDesc);
        }
    }

    public void ApplyDispatchBehavior(ContractDescription description, ServiceEndpoint endpoint, System.ServiceModel.Dispatcher.DispatchRuntime dispatch)
    {
        foreach (OperationDescription opDesc in description.Operations)
        {
            ApplyDataContractSurrogate(opDesc);
        }
    }

    private static void ApplyDataContractSurrogate(OperationDescription description)
    {
        DataContractSerializerOperationBehavior dcsOperationBehavior = description.Behaviors.Find<DataContractSerializerOperationBehavior>();
        if (dcsOperationBehavior != null)
        {
            if (dcsOperationBehavior.DataContractSurrogate == null)
                dcsOperationBehavior.DataContractSurrogate = new NHProxyDataContractSurrogate();
        }
    }

    public void AddBindingParameters(ContractDescription contractDescription, ServiceEndpoint serviceEndPoint, BindingParameterCollection parameters) { }

    public void Validate(ContractDescription contractDescription, ServiceEndpoint serviceEndPoint) { }
}

和应用自定义属性,以我的ServiceContract:

And applied the custom attribute to my ServiceContract:

[ServiceContract]
[CanSerializeNHProxy]
public interface IElementManager
{ ... }

我得到了很多有用的信息,从这些链接:

I got a lot of useful info from these links:

DataContractSurrogate MSDN页,指向自定义属性

DataContractSurrogate实现对象

希望这有助于。

阅读全文

相关推荐

最新文章