简体   繁体   中英

REST WCF service - differences data input format (JSON/XML)

maybe this is a dumb question, but I need some help.

I'm using WCF to make a restful service. Users send me data to my methods through http post request.

I have done one method receiving a string representing data in json format. So, I simply parse it and create my object to read.

My dumb question is: how can I set another method to be able to receive data input in XML format? I mean, for json I simply expect a string to parse. For XML?

This is my first time with this issue and I'd like to learn how to do it in a clean way (like the string for json).

Can you help me?

UPDATE: For example, I have this sample method:

    [OperationContract]
    [WebInvoke(UriTemplate = "Patient/Add", Method = "POST")]
    int AddPatient(Patient patient);

I see the input is a custom class... so, I think clients can send me an xml representing this class.. or not? Can I simply manage the input like this?

Personally I use something like this.

    [OperationContract]
    [WebInvoke(Method = "POST",
        RequestFormat = WebMessageFormat.Json,
        ResponseFormat = WebMessageFormat.Json,
        UriTemplate = "json")]
    void AddUsefulLinkJson(UsefulLinksWCF.Models.UsefulLink link);

    [OperationContract]
    [WebInvoke(Method = "POST",
        RequestFormat = WebMessageFormat.Xml,
        ResponseFormat = WebMessageFormat.Xml,
        UriTemplate = "xml")]
    void AddUsefulLinkXml(UsefulLinksWCF.Models.UsefulLink link);

So then when you use a client you can request data in json or xml like this:

http://www.something.com/UsefulLinks/rest/xml

or

http://www.something.com/UsefulLinks/rest/json

There is a good article on MSDN regarding format selection starting from NET 4.0:

https://msdn.microsoft.com/en-us/library/ee476510%28v=vs.100%29.aspx

When enabled, automatic formatting chooses the best format in which to return the response. It determines the best format by checking the following, in order:

The media types in the request message's Accept header.

The content-type of the request message.

The default format setting in the operation.

The default format setting in the WebHttpBehavior.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM