WCF REST Service - Diff Input Format (JSON / XML)
This might be a stupid question, but I need help.
I am using WCF to create a quiet service. Users send me data to my methods via http post request.
I made one method that gets a string representing data in json format. So, I just parse it and create my readable object.
My dumb question is, how can I set a different method to get data in XML format? I mean, for json, I just expect the string to be parsed. For XML?
This is my first time with this problem, and I would like to know how to do it in a clean way (like string for json).
Can you help me?
UPDATE: For example, I have this method:
[OperationContract]
[WebInvoke(UriTemplate = "Patient/Add", Method = "POST")]
int AddPatient(Patient patient);
I can see that the injected custom class ... so I guess clients can send me an xml representing this class .. or not? Can I just control the input this way?
source to share
I personally 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, when you are using 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 since NET 4.0:
https://msdn.microsoft.com/en-us/library/ee476510%28v=vs.100%29.aspx
When enabled, automatic formatting chooses the best format to return the response. It determines the best format by checking the following to:
Media types in request messages. Accept heading.
The content type of the request message.
Setting the default format in the operation.
Setting the default format in WebHttpBehavior.
source to share