2

我按照本指南创建了我的自定义格式化程序,因此我可以使用 Newtonsoft Json.NET 进行对象序列化,因为内置的 Microsoft 不支持父/子关系的循环。

http://blogs.msdn.com/b/carlosfigueira/archive/2011/05/03/wcf-extensibility-message-formatters.aspx

在他的示例中,他手动创建了他的 ServiceHost。我正在利用本指南教给我的 Routes 和 WebServiceFactory。

http://blogs.msdn.com/b/endpoint/archive/2010/01/06/introducing-wcf-webhttp-services-in-net-4.aspx

据我所知,我只需要找出一种将适当的行为添加到我的服务端点的方法。任何帮助我指出正确的方向将不胜感激。

下面是一些代码片段,以方便参考...


在我的 Global.asax

        WebServiceHostFactory webServiceHostFactory = new WebServiceHostFactory();
        RouteTable.Routes.Add(new ServiceRoute(Accounts.Route, webServiceHostFactory, typeof(Accounts)));

如果我的 web.config

<serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
<standardEndpoints>
    <webHttpEndpoint>
    <!-- 
        Configure the WCF REST service base address via the global.asax.cs file and the default endpoint 
        via the attributes on the <standardEndpoint> element below
    -->
    <standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="false" defaultOutgoingResponseFormat="Json"/>
    </webHttpEndpoint>
</standardEndpoints>

在他的程序的主要功能中

        string baseAddress = "http://" + Environment.MachineName + ":8000/Service";
        ServiceHost host = new ServiceHost(typeof(Service), new Uri(baseAddress));
        host.AddServiceEndpoint(typeof(ITestService), new BasicHttpBinding(), "soap");
        WebHttpBinding webBinding = new WebHttpBinding();
        webBinding.ContentTypeMapper = new MyRawMapper();
        host.AddServiceEndpoint(typeof(ITestService), webBinding, "json").Behaviors.Add(new NewtonsoftJsonBehavior());
4

1 回答 1

1

要使用路由并获取对服务端点的引用,您需要自定义服务主机工厂。它可以与您当前使用的 WebServiceHostFactory 执行相同的操作(只需返回对 WebServiceHost 的引用),而是返回对您的自定义服务主机的引用。

您可以在http://blogs.msdn.com/b/carlosfigueira/archive/2011/06/14/wcf-extensibility-servicehostfactory.aspx找到有关服务主机工厂的更多信息。

public class MyServiceHostFactory : ServiceHostFactory
{
    protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)
    {
        return base.CreateServiceHost(serviceType, baseAddresses);
    }

    class MyServiceHost : WebServiceHost
    {
        public MyServiceHost(Type serviceType, Uri[] baseAddresses)
            : base(serviceType, baseAddresses)
        { }

        protected override void OnOpening()
        {
            base.OnOpening();

            foreach (ServiceEndpoint endpoint in this.Description.Endpoints)
            {
                CustomBinding custom = endpoint.Binding as CustomBinding;
                if (custom != null)
                {
                    custom = new CustomBinding(endpoint.Binding);
                }

                custom.Elements.Find<WebMessageEncodingBindingElement>().ContentTypeMapper = new MyRawMapper();
                endpoint.Binding = custom;

                endpoint.Behaviors.Add(new NewtonsoftJsonBehavior());
            }
        }
    }
}
于 2011-07-15T02:39:52.517 回答