Asp.net mvc返回Xml結果,擴展Controller實現XmlResult以返回XML格式數據

来源:http://www.cnblogs.com/xiongzaiqiren/archive/2016/01/05/XmlResult.html
-Advertisement-
Play Games

我們都知道Asp.net MVC自帶的Action可以有多種類型,比如ActionResult,ContentResult,JsonResult……,但是很遺憾沒有支持直接返回XML的XmlResult。當然,你也可以用ActionResult或者ContentResult,然後直接返回xml字元串...


我們都知道Asp.net MVC自帶的Action可以有多種類型,比如ActionResult,ContentResult,JsonResult……,但是很遺憾沒有支持直接返回XML的XmlResult。

當然,你也可以用ActionResult或者ContentResult,然後直接返回xml字元串。

如果我們想要想JsonResult一樣來調用和返回xml結果,我們可以自己新建擴展XmlResult,該怎麼辦呢?不多說,看下麵實例:

 

第一步,擴展System.Web.Mvc XmlRequestBehavior

/// <summary>
/// 擴展System.Web.Mvc XmlRequestBehavior
/// 指定是否允許來自客戶端的HTTP GET請求
/// 熊仔其人/// </summary>
public enum XmlRequestBehavior
{
    /// <summary>
    /// HTTP GET requests from the client are allowed.
    /// 允許來自客戶端的HTTP GET請求
    /// </summary>      
    AllowGet = 0,
    /// <summary>
    /// HTTP GET requests from the client are not allowed.
    /// 不允許來自客戶端的HTTP GET請求
    /// </summary>
    DenyGet = 1,
}

 

第二步,實現XmlResult繼承ActionResult

/// <summary>
/// 實現XmlResult繼承ActionResult
/// 擴展MVC的ActionResult支持返回XML格式結果
/// 熊仔其人/// </summary>
public class XmlResult : ActionResult
{
    /// <summary>
    /// Initializes a new instance of the System.Web.Mvc.XmlResult class
    /// 初始化
    /// </summary>         
    public XmlResult() { }
    /// <summary>
    /// Encoding
    /// 編碼格式
    /// </summary>
    public Encoding ContentEncoding { get; set; }
    /// <summary>
    /// Gets or sets the type of the content.
    /// 獲取或設置返回內容的類型
    /// </summary>
    public string ContentType { get; set; }
    /// <summary>
    /// Gets or sets the data
    /// 獲取或設置內容
    /// </summary>
    public object Data { get; set; }
    /// <summary>
    /// Gets or sets a value that indicates whether HTTP GET requests from the client
    /// 獲取或設置一個值,指示是否HTTP GET請求從客戶端
    /// </summary>
    public XmlRequestBehavior XmlRequestBehavior { get; set; }
    /// <summary>
    /// Enables processing of the result of an action method by a custom type that
    /// 處理結果
    /// </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); // 把數據序列化到記憶體流中                     
                ms.Position = 0;
                using (StreamReader sr = new StreamReader(ms))
                {
                    context.HttpContext.Response.Output.Write(sr.ReadToEnd()); // 輸出流對象 
                }
            }
        }
    }
}

 

註釋:如果想要修改反序列化後的xml命名空間,可以使用自定義命名空間:

//使用你的定義的命名空間名稱
var ns = new XmlSerializerNamespaces();
ns.Add("xsi", "http://api.xxxx.com/1.0/");

然後這裡添加自定義命名空間,註意第三個參數
xs.Serialize(ms, Data ,ns); // 把數據序列化到記憶體流中 

 

 

第三步,擴展System.Mvc.Controller

/// <summary>
/// 擴展System.Mvc.Controller
/// 熊仔其人/// </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 }; }
}

 

到此就完成啦,下麵就看看怎麼調用:

第四步,在Controller里調用XmlResult

public ActionResult GetActionResult(string type)
{
    var data = new List<string>(); //註意,data必須是可被序列化的內容
    data.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("不支持此方法");
    }
}

public XmlResult GetXml()
{
    var data = new List<string>(); //註意,data必須是可被序列化的內容
    data.Add("A");
    data.Add("B");
    data.Add("C");
    return this.Xml(data, XmlRequestBehavior.AllowGet);
}

運行一下,看看實際返回結果吧!

上面的示例運行發揮的結果是這樣:

<?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>

 

以下是完整的代碼:

using System;
using System.IO;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Xml.Serialization;

namespace Onexz.API.Models
{
    /// <summary>
    /// 擴展System.Web.Mvc XmlRequestBehavior
    /// 指定是否允許來自客戶端的HTTP GET請求
    /// 熊仔其人/// </summary>
    public enum XmlRequestBehavior
    {
        /// <summary>
        /// HTTP GET requests from the client are allowed.
        /// 允許來自客戶端的HTTP GET請求
        /// </summary>      
        AllowGet = 0,
        /// <summary>
        /// HTTP GET requests from the client are not allowed.
        /// 不允許來自客戶端的HTTP GET請求
        /// </summary>
        DenyGet = 1,
    }

    /// <summary>
    /// 實現XmlResult繼承ActionResult
    /// 擴展MVC的ActionResult支持返回XML格式結果
    /// 熊仔其人/// </summary>
    public class XmlResult : ActionResult
    {
        /// <summary>
        /// Initializes a new instance of the System.Web.Mvc.XmlResult class
        /// 初始化
        /// </summary>         
        public XmlResult() { }
        /// <summary>
        /// Encoding
        /// 編碼格式
        /// </summary>
        public Encoding ContentEncoding { get; set; }
        /// <summary>
        /// Gets or sets the type of the content.
        /// 獲取或設置返回內容的類型
        /// </summary>
        public string ContentType { get; set; }
        /// <summary>
        /// Gets or sets the data
        /// 獲取或設置內容
        /// </summary>
        public object Data { get; set; }
        /// <summary>
        /// Gets or sets a value that indicates whether HTTP GET requests from the client
        /// 獲取或設置一個值,指示是否HTTP GET請求從客戶端
        /// </summary>
        public XmlRequestBehavior XmlRequestBehavior { get; set; }
        /// <summary>
        /// Enables processing of the result of an action method by a custom type that
        /// 處理結果
        /// </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); // 把數據序列化到記憶體流中                     
                    ms.Position = 0;
                    using (StreamReader sr = new StreamReader(ms))
                    {
                        context.HttpContext.Response.Output.Write(sr.ReadToEnd()); // 輸出流對象 
                    }
                }
            }
        }
    }

    /// <summary>
    /// 擴展System.Mvc.Controller
    /// 熊仔其人/// </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 }; }
    }

}

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...