An XmlResult for ASP.NET MVC
Introduction
ActionResult methods in a Controller allow developers to easily return HTML results and JSON results via this.View(...) which creates a ViewResult and this.Json(...) which creates a JsonResult. [See the following MSDN resources for more information: Controller.View method and Controller.Json method.]
Unfortunately, there is no XmlResult type that derives from ActionResult.
Although there are WCF ways of returning XML in an ASP.NET MVC application, there are use cases where returning simple POX (plain old XML) from a call to an MVC Controller ActionResult is needed.
In this article, I'll show a simple way to create an XmlResult.
How to create an XmlResult
Requirements
An XmlResult should
- Inherit from
ViewResult, - Override the
ExecuteResultmethod to write the XML, - Expose the object to serialize as a gettable property, and
- Allow calling code to customize the XML produced.
The ExecuteResult override should
- Do nothing if there is no object to serialize,
- Use the
XmlAttributeOverridesif there are any, - Set the
ContentTypeof theResponsetoapplication/xml, and - Write the XML-serialized version of the object to serialize to the
Outputstream of theResponse.
XmlResult Code
Below is code that meets these requirements:
How to extend Controller to easily return an XmlResult
It is desirable to be able to have an ActionResult method in a Controller be able to obtain an XmlResult via a this.XML(...) statement.
This can be accomplished via an Extension Method.
Requirements
The Controller.XML extension method should
- Accept an object to serialize,
- Optionally accept
XmlAttributeOverrides, and - Return an
XmlResult.
Code
Below is code that meets these requirements:
Conclusion
This article shows a simple way to create an XmlResult to return XML that can be used within an ASP.NET MVC Controller, and a way to extend Controller to allow for easy use.
This approach is appropriate for simple needs and eliminates the need to write custom code each time XML is needed.
For more complicated needs, using a ContentResult offers a feasible approach.
No comments:
Post a Comment