Asp.net mvc returns Xml results, extended Controller implements XmlResult to return XML format data, mvcxmlresult

Source: Internet
Author: User

Asp.net mvc returns Xml results, extended Controller implements XmlResult to return XML format data, mvcxmlresult

We all know that the Action that comes with Asp.net MVC can have multiple types, such as ActionResult, ContentResult, JsonResult ......, Unfortunately, XML XmlResult is not directly returned.

Of course, you can also use ActionResult or ContentResult to directly return an xml string.

If we want to call and return xml results like JsonResult, we can create new XmlResult extension by ourselves. What should we do? Let's talk about the following example:

 

Step 1: expand System. Web. Mvc XmlRequestBehavior

/// <Summary> /// extended System. web. mvc XmlRequestBehavior // specify whether to allow http get requests from the client // The owner of the bear /// </summary> public enum XmlRequestBehavior {// <summary> // HTTP GET requests from the client are allowed. /// allow http get requests from the client /// </summary> AllowGet = 0, /// <summary> // http get requests from the client are not allowed. /// http get requests from the client are not allowed /// </summary> DenyGet = 1 ,}

 

Step 2: Implement XmlResult to inherit ActionResult

/// <Summary> /// implement XmlResult to inherit ActionResult /// support returning XML format results by extending the MVC ActionResult /// the owner of the bear /// </summary> public class XmlResult: actionResult {// <summary> // Initializes a new instance of the System. web. mvc. xmlResult class // initialization /// </summary> public XmlResult () {}/// <summary> /// Encoding // Encoding format /// </summary> public Encoding ContentEncoding {get; set ;} /// <summary> // Gets or sets the type Of the content. /// obtain or set the type of the returned content /// </summary> public string ContentType {get; set ;} /// <summary> // Gets or sets the data // get or set the content /// </summary> public object Data {get; set ;} /// <summary> // Gets or sets a value that indicates whether http get requests from the client // Gets or sets a value, indicates whether the http get request is from the client // </summary> public XmlRequestBehavior {get; set ;}/// <summ Ary> // Enables processing of the result of an action method by a custom type that // processing result // </summary> /// <param name = "context "> </param> public override void ExecuteResult (ControllerContext context) {if (context = null) {throw new ArgumentNullException ("context");} HttpRequestBase request = context. httpContext. request; if (XmlRequestBehavior = XmlRequestBehavior. denyGet & string. equals (Context. httpContext. request. httpMethod, "GET", StringComparison. ordinalIgnoreCase) {throw new InvalidOperationException ("XmlRequest_GetNotAllowed");} HttpResponseBase response = context. httpContext. response; response. contentType =! String. IsNullOrEmpty (this. ContentType )? This. ContentType: "application/xml"; if (this. ContentEncoding! = Null) {response. ContentEncoding = this. ContentEncoding;} if (Data! = Null) {using (MemoryStream MS = new MemoryStream () {XmlSerializer xs = new XmlSerializer (Data. getType (); xs. serialize (ms, Data); // Serialize Data to memory streams in ms. position = 0; using (StreamReader sr = new StreamReader (MS) {context. httpContext. response. output. write (sr. readToEnd (); // output stream object }}}}}

 

Note: To modify the deserialization xml namespace, you can use the custom namespace:

// Use your defined namespace name var ns = new XmlSerializerNamespaces (); ns. add ("xsi", "http://api.xxxx.com/1.0/"); then Add the custom namespace here, note the third parameter xs. serialize (MS, Data, ns); // Serialize Data to a memory stream

 

 

Step 3: expand System. Mvc. Controller

/// <Summary> /// extended System. mvc. controller // The owner of the bear child /// </summary> public static class ControllerExtension {public static XmlResult Xml (this Controller request, object obj) {return Xml (obj, null, null, xmlRequestBehavior. denyGet);} public static XmlResult Xml (this Controller request, object obj, XmlRequestBehavior behavior) {return Xml (obj, null, null, behavior );} public static XmlResult Xml (this Controller request, object obj, Encoding contentEncoding, XmlRequestBehavior behavior) {return Xml (obj, null, contentEncoding, behavior );} public static XmlResult Xml (this Controller request, object obj, string contentType, Encoding contentEncoding, XmlRequestBehavior behavior) {return Xml (obj, contentType, contentEncoding, behavior );} internal static XmlResult Xml (object data, string contentType, Encoding contentEncoding, XmlRequestBehavior behavior) {return new XmlResult () {ContentEncoding = contentEncoding, ContentType = contentType, Data = data, xmlRequestBehavior = behavior };}}

 

Now, let's take a look at how to call it:

Step 4: Call XmlResult in the Controller

Public ActionResult GetActionResult (string type) {var data = new List <string> (); // note that data must be serialized. add ("A"); data. add ("B"); data. add ("C"); if (type. toLower () = "xml") {return this. xml (data, XmlRequestBehavior. allowGet);} else if (type. toLower () = "json") {return Json (data, JsonRequestBehavior. allowGet);} else {// error messages return View ("this method is not supported");} public XmlResult GetXml () {var data = new List <string> (); // note that data must be serialized. add ("A"); data. add ("B"); data. add ("C"); return this. xml (data, XmlRequestBehavior. allowGet );}

Run the command to check the actual returned results!

The result of the preceding example is as follows:

<? Xml version = "1.0"?>
<ArrayOfString xmlns: xsd = "http://www.w3.org/2001/XMLSchema" xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance">
<String> A </string>
<String> B </string>
<String> C </string>
</ArrayOfString>

 

The complete code is as follows:

Using System; using System. IO; using System. text; using System. web; using System. web. mvc; using System. xml. serialization; namespace Onexz. API. models {/// <summary> /// extended System. web. mvc XmlRequestBehavior // specify whether to allow http get requests from the client // The owner of the bear /// </summary> public enum XmlRequestBehavior {// <summary> // HTTP GET requests from the client are allowed. /// allow http get requests from the client /// </summary> AllowGet = 0 ,/// <Summary> // http get requests from the client are not allowed. /// http get requests from the client are not allowed /// </summary> DenyGet = 1 ,} /// <summary> /// implement XmlResult to inherit ActionResult /// support returning XML format results by extending the MVC ActionResult /// the owner of the bear /// </summary> public class XmlResult: actionResult {// <summary> // Initializes a new instance of the System. web. mvc. xmlResult class // initialization /// </summary> public XmlResult () {}/// <summa Ry >/// Encoding /// Encoding format /// </summary> public Encoding ContentEncoding {get; set ;} /// <summary> // Gets or sets the type of the content. /// obtain or set the type of the returned content /// </summary> public string ContentType {get; set ;} /// <summary> // Gets or sets the data // get or set the content /// </summary> public object Data {get; set ;} /// <summary> // Gets or sets a value that indicates whether http get requests from The client // gets or sets a value indicating whether an http get request is sent from the client // </summary> public XmlRequestBehavior {get; set ;} /// <summary> // Enables processing of the result of an action method by a custom type that // processing result /// </summary> // <param name = "context"> </param> public override void ExecuteResult (ControllerContext context) {if (context = null) {throw new ArgumentNullException ("context ");} HttpRequestBase request = context. httpContext. request; if (XmlRequestBehavior = XmlRequestBehavior. denyGet & string. equals (context. httpContext. request. httpMethod, "GET", StringComparison. ordinalIgnoreCase) {throw new InvalidOperationException ("XmlRequest_GetNotAllowed");} HttpResponseBase response = context. httpContext. response; response. contentType =! String. IsNullOrEmpty (this. ContentType )? This. ContentType: "application/xml"; if (this. ContentEncoding! = Null) {response. ContentEncoding = this. ContentEncoding;} if (Data! = Null) {using (MemoryStream MS = new MemoryStream () {XmlSerializer xs = new XmlSerializer (Data. getType (); xs. serialize (ms, Data); // Serialize Data to memory streams in ms. position = 0; using (StreamReader sr = new StreamReader (MS) {context. httpContext. response. output. write (sr. readToEnd (); // output stream object }}}/// <summary> // extended System. mvc. controller // The owner of the bear child /// </summary> public static class ControllerExtension {public static XmlResult Xml (this Controller request, object obj) {return Xml (obj, null, null, xmlRequestBehavior. denyGet);} public static XmlResult Xml (this Controller request, object obj, XmlRequestBehavior behavior) {return Xml (obj, null, null, behavior );} public static XmlResult Xml (this Controller request, object obj, Encoding contentEncoding, XmlRequestBehavior behavior) {return Xml (obj, null, contentEncoding, behavior );} public static XmlResult Xml (this Controller request, object obj, string contentType, Encoding contentEncoding, XmlRequestBehavior behavior) {return Xml (obj, contentType, contentEncoding, behavior );} internal static XmlResult Xml (object data, string contentType, Encoding contentEncoding, XmlRequestBehavior behavior) {return new XmlResult () {ContentEncoding = contentEncoding, ContentType = contentType, Data = data, xmlRequestBehavior = behavior };}}}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.