Wahlin on .NET

Return XML from AJAX-Enabled Web Services

Dan walks you through using the ScriptMethod Attribute.

ASP.NET AJAX-enabled Web services return JSON formatted messages (see my previous articles, here and here) by default since SOAP messages can't be parsed by all browsers.  While converting request and response messages to JSON offers the best cross-browser solution, there may be situations where you need to return XML messages instead of JSON to simplify data processing on the client. For example, a Web service may access RSS data and return it directly to the browser for display in an Intranet scenario where Internet Explorer 5 or higher is used.

By returning XML data, XSLT and XML DOM programming interfaces can be used to transform XML data into other formats with relative ease. Keep in mind that Internet Explorer is currently the only browser to offer robust support for both DOM APIs and XSLT (FireFox has only limited support), so the solution presented in this article is not intended to work across multiple browsers (although that may change as the browsers continue to offer more XML-related features).The solution shown is specific to Internet Explorer 5 or higher deployed in an Intranet environment.

Using the ScriptMethod Attribute
The ASP.NET AJAX Extensions provide a class named ScriptMethodAttribute that can be applied to Web methods in a Web service. By using the ScriptMethodAttribute class, clients can make GET requests instead of POST requests when calling a service and can receive XML data instead of JSON data. ScriptMethodAttribute exposes three properties including UseHttpGet (which accepts a Boolean value), ResponseFormat (which can be set to a ResponseFormat enumeration value), and XmlSerializeString (which can be set to a Boolean value).

I won't discuss the UseHttpGet property in this article, but I do want to mention that you should only change to GET when you're absolutely sure that sensitive data isn't going to be passed to and from a Web service. Sticking with the default POST verb is recommended. An example of using the UseHttpGet property is available in the downloadable code for this article.

When you'd like a Web method to return XML data, you can set the ResponseFormat property to a value of ResponseFormat.Xml as shown below.

 
[ScriptMethod(ResponseFormat = ResponseFormat.Xml)]
[WebMethod]
public XmlElement GetRssFeed(string url)
{
    XmlDocument doc = new XmlDocument();
    doc.Load(url);
    return doc.DocumentElement;
}

In cases where Web methods return string values that you'd like wrapped in an XML tag, you can set the XmlSerializeString property to true as shown below. This will wrap the returned string with <string></string> tags.

[ScriptMethod(ResponseFormat = 
  ResponseFormat.Xml,XmlSerializeString=true)]
[WebMethod]
public string GetXmlString(string input)
{
    return input;
}

XML data returned from a Web service can be processed easily in Internet Explorer 5 or higher by using XSLT stylesheets or DOM APIs. Parsing RSS data returned from a service is fairly straightforward because XPath expressions can be used along with DOM methods to locate <item>, <title>, and <link> tags within the RSS data. The XPath language allows XML documents to be queried to locate desired data in an XML document More information about the XPath language can be found at http://www.w3.org/TR/xpath.

Listing 1 shows an example of calling a Web method that has been marked with the ScriptMethodAttribute class and had its ResponseFormat property set to ResponseFormat.Xml. The returned data is parsed using the client-side selectNodes() and selectSingleNode() methods, which accept XPath expressions. Data extracted from the XML response is written out to the page so that an end user can click on a link to view more details. This example parses my blog here.

The default JSON message format using in ASP.NET AJAX should be leveraged wherever possible when working in a cross-browser environment.  However, in cases where a browser with XML parsing support is available, you can use the ScriptMethodAttribute class to send XML responses to the client.

About the Author

Dan Wahlin (Microsoft MVP for ASP.NET and XML Web Services) is the founder of The Wahlin Group which specializes in .NET and SharePoint onsite, online and video training and consulting solutions. Dan also founded the XML for ASP.NET Developers Web site, which focuses on using ASP.NET, XML, AJAX, Silverlight and Web Services in Microsoft's .NET platform. He's also on the INETA Speaker's Bureau and speaks at conferences and user groups around the world. Dan has written several books on .NET including "Professional Silverlight 2 for ASP.NET Developers," "Professional ASP.NET 3.5 AJAX, ASP.NET 2.0 MVP Hacks and Tips," and "XML for ASP.NET Developers." Read Dan's blog here.

comments powered by Disqus

Featured

  • Compare New GitHub Copilot Free Plan for Visual Studio/VS Code to Paid Plans

    The free plan restricts the number of completions, chat requests and access to AI models, being suitable for occasional users and small projects.

  • Diving Deep into .NET MAUI

    Ever since someone figured out that fiddling bits results in source code, developers have sought one codebase for all types of apps on all platforms, with Microsoft's latest attempt to further that effort being .NET MAUI.

  • Copilot AI Boosts Abound in New VS Code v1.96

    Microsoft improved on its new "Copilot Edit" functionality in the latest release of Visual Studio Code, v1.96, its open-source based code editor that has become the most popular in the world according to many surveys.

  • AdaBoost Regression Using C#

    Dr. James McCaffrey from Microsoft Research presents a complete end-to-end demonstration of the AdaBoost.R2 algorithm for regression problems (where the goal is to predict a single numeric value). The implementation follows the original source research paper closely, so you can use it as a guide for customization for specific scenarios.

  • Versioning and Documenting ASP.NET Core Services

    Building an API with ASP.NET Core is only half the job. If your API is going to live more than one release cycle, you're going to need to version it. If you have other people building clients for it, you're going to need to document it.

Subscribe on YouTube