WCF Service contract to be both XML and Json serialized

只谈情不闲聊 提交于 2020-01-24 10:38:14

问题


How can I create the service contract to be in XmlSerializerFormat as well as WebMessageFormat.Json within a WCF RESTful service.

What I need is to call the "CallADSWebMethod" operation contract from code behind of ASP.Net 1.1 which needs to be XML serialized and from jQuery ajax which is Json serialized.

SERVICE CONTRACT

[ServiceContract, XmlSerializerFormat]
    public interface IService
    {
        [OperationContract, XmlSerializerFormat]
        [WebInvoke(UriTemplate = "/CallADSWebMethod",
                   Method = "POST",
                   BodyStyle = WebMessageBodyStyle.WrappedRequest,
                   ResponseFormat = WebMessageFormat.Json)]
        VINDescription CallADSWebMethod(string vin, string styleID);
    }

Endpoint Info

        <endpoint address="basic"
                  binding="basicHttpBinding"
                  name="httpEndPoint"
                  contract="ADSChromeVINDecoder.IService" />
        <endpoint address="json"
                  binding="webHttpBinding"
                  behaviorConfiguration="webBehavior"
                  name="webEndPoint"
                  contract="ADSChromeVINDecoder.IService" />
        <endpoint contract="IMetadataExchange"
                  binding="mexHttpBinding"
                  address="mex" />

回答1:


What you can do is specify your Web Service like this:

     [OperationContract]
    [WebInvoke(Method = "POST", 
        ResponseFormat = WebMessageFormat.Xml, 
        BodyStyle = WebMessageBodyStyle.WrappedRequest, 
        UriTemplate = ""/CallADSWebMethod"")]
    [WebInvoke(Method = "POST",
        ResponseFormat = WebMessageFormat.Json,
        BodyStyle = WebMessageBodyStyle.WrappedRequest,
        UriTemplate = ""/CallADSWebMethod"")]
VINDescription CallADSWebMethod(string vin, string styleID);
    }

However, what I would suggest you to do is specify 2 different endpoints: one for the XML serialized data and another for JSON serialized data. Come on dude, you are using the REST architecture.....why not make full use of it??!




回答2:


This can actually be done without a dual declaration as shown in this answer by setting the webHttpBehavior's automaticFormatSelectionEnabled property to true.



来源:https://stackoverflow.com/questions/12947438/wcf-service-contract-to-be-both-xml-and-json-serialized

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!