简体   繁体   中英

Separate web service for JSON and XML?

I'm setting out to write a web service in C# which will be consumed by clients which may require either JSON or XML.

I understand .Net can do this very well as long as you are returning something simple like this person object in your WebMethod

class person
{
    string name
    string age
}

The purpose of this web service is to act as a layer between the database and the clients and I'll be getting the data via stored procedures which will only ever contain one table.

I've tried simply returning a datatable, but that doesn't play nice with JSON (circular reference issues if you consume as application/json ). Is the best solution in this case to create serializable classes that I can map my data to? The reason I'm asking is that this will be very cumbersome.

Alternatively I can create a separate web service for each and write a bit of code to efficiently map datatable column names to fields to cater for JSON and just return the string.

The best practice is indeed to create separate, simple UI objects which can be passed back to the client. although a pain, this will decouple your front end service code from your data layer, and allow you to change the data without affecting the objects that the client consumes.

You won't however need to create separate web services. I believe you can create 2 different endpoints for the same service, and configure them to to return xml/json depending on which address (endpoint) is used by the client.

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