WCF Service contract to be both XML and Json seria

2019-07-03 13:02发布

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" />

2条回答
Fickle 薄情
2楼-- · 2019-07-03 13:21

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??!

查看更多
一纸荒年 Trace。
3楼-- · 2019-07-03 13:35

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

查看更多
登录 后发表回答