I’m writing a page that needs to exchange some information with a SQL server. For portability reasons, and because I hate writing ASP but I’ve been told to do this on the IIS 7 server, I’m writing the page in pure HTML, a generic handler (ASHX) in C# .NET to do the server-side stuff, and using AJAX to communicate between them. I’ve got this approach working using Response.ContentType = "text/plain";, but I’d like to return several pieces of information with one request, so I’m switching to XML or JSON, leaning toward XML.
So, to return XML, I change to "text/xml", but then do I just Response.Write the whole XML code verbatim, or is there a more succinct way built into .NET? Same question for JSON. I know there are specific methods in jQuery (even just JavaScript) for parsing the returned data, so I was wondering if there was something similar in .NET to encode.
You could use a XmlWriter, XDocument or even a XmlSerializer to build the XML and then write it to the
Response.OutputStream.Here’s an example with a
XDocument:You would use a Json serializer such as JavaScriptSerializer and then write it to the output stream:
This being said, you should be aware that ASP.NET MVC or the knocking on the door Web API are now the preferred ways to expose such data instead of writing generic handlers.