ASP.NET MVC中常用的ActionResult類型

来源:https://www.cnblogs.com/supersnowyao/archive/2018/01/15/8287775.html
-Advertisement-
Play Games

一、定義 MVC中ActionResult是Action的返回結果。ActionResult 有多個派生類,每個子類功能均不同,並不是所有的子類都需要返回視圖View,有些直接返迴流,有些返回字元串等。ActionResult是一個抽象類,它定義了唯一的ExecuteResult方法,參數為一個Co ...


一、定義

     MVC中ActionResult是Action的返回結果。ActionResult 有多個派生類,每個子類功能均不同,並不是所有的子類都需要返回視圖View,有些直接返迴流,有些返回字元串等。ActionResult是一個抽象類,它定義了唯一的ExecuteResult方法,參數為一個ControllerContext,下麵為您介紹MVC中的ActionResult 的用法。

二、什麼是ActionResult

     ActionResult是控制器方法執行後返回的結果類型,控制器方法可以返回一個直接或間接從ActionResult抽象類繼承的類型,如果返回的 是非ActionResult類型,控制器將會將結果轉換為一個ContentResult類型。預設的ControllerActionInvoker 調用ActionResult.ExecuteResult方法生成應答結果。

三、常見的ActionResult

     1、ViewResult

     表示一個視圖結果,它根據視圖模板產生應答內容。對應得Controller方法為View。

     2、PartialViewResult

     表示一個部分視圖結果,與ViewResult本質上一致,只是部分視圖不支持母版,對應於ASP.NET,ViewResult相當於一個Page,而PartialViewResult 則相當於一個UserControl。它對應得Controller方法的PartialView.

     3、RedirectResult

       表示一個連接跳轉,相當於ASP.NET中的Response.Redirect方法,對應得Controller方法為Redirect。

     4、RedirectToRouteResult

     同樣表示一個跳轉,MVC會根據我們指定的路由名稱或路由信息(RouteValueDictionary)來生成Url地址,然後調用Response.Redirect跳轉。對應的Controller方法為RedirectToAction和RedirectToRoute.

     5、ContentResult

     返回簡單的純文本內容,可通過ContentType屬性指定應答文檔類型,通過ContentEncoding屬性指定應答文檔的字元編碼。可通過Controller類中的Content方法便捷地返回ContentResult對象。如果控制器方法返回非ActionResult對象,MVc將簡單地以返回對象的toString()內容為基礎產生一個ContentResult對象。

     6、EmptyResult

     返回一個空的結果,如果控制器方法返回一個null ,MVC將其轉換成EmptyResult對象。

     7、JavaScriptResult

     本質上是一個文本內容,只是將Response.ContentType設置為application/x-javascript,此結果應該和MicrosoftMvcAjax.js腳本配合使用,客戶端接收到Ajax應答後,將判斷Response.ContentType的值,如果是application/x-javascript,則直接eval 執行返回的應答內容,此結果類型對應得Controller方法為JavaScript.

     8、JsonResult

     表示一個Json結果。MVC將Response.ContentType 設置為application/json,並通過JavaScriptSerializer類指定對象序列化為Json表示方式。需要註意,預設情況下,Mvc不允許GET請求返回Json結果,要解除此限制,在生成JsonResult對象時,將其JsonRequestBehavior屬性設置為JsonRequestBehavior.AllowGet,此結果對應Controller方法的Json.

     9、FileResult(FilePathResult、FileContentResult、FileStreamResult)

     這三個類繼承於FileResult,表示一個文件內容,三者區別在於,FilePath 通過路徑傳送文件到客戶端,FileContent 通過二進位數據的方式,而FileStream 是通過Stream(流)的方式來傳送。Controller為這三個文件結果類型提供了一個名為File的重載方法。

     FilePathResult: 直接將一個文件發送給客戶端

     FileContentResult: 返回byte位元組給客戶端(比如圖片)

     FileStreamResult: 返迴流

     10、HttpUnauthorizedResult

     表示一個未經授權訪問的錯誤,MVC會向客戶端發送一個401的應答狀態。如果在web.config 中開啟了表單驗證(authenication mode=”Forms”),則401狀態會將Url 轉向指定的loginUrl 鏈接。

     11、HttpStatusCodeResult

     返回一個伺服器的錯誤信息

     12、HttpNoFoundResult

     返回一個找不到Action錯誤信息

四、ActionResult子類之間的關係表

    

五、ActionResult(12種)的簡單應用

     源碼:

  1 using StudyMVC4.Models;
  2 using System;
  3 using System.Collections.Generic;
  4 using System.IO;
  5 using System.Linq;
  6 using System.Net;
  7 using System.Net.Http;
  8 using System.Web.Http;
  9 using System.Web.Mvc;
 10 
 11 namespace StudyMVC4.Controllers
 12 {
 13     public class HomeController : Controller
 14     {
 15        
 16         public ActionResult Index() {
 17             return View();
 18         }
 19 
 20         /// <summary>
 21         /// ContentResult用法(返迴文本)
 22         /// http://localhost:30735/home/ContentResultDemo
 23         /// </summary>
 24         /// <returns>返迴文本</returns>
 25         public ActionResult ContentResultDemo(){
 26             string str = "ContentResultDemo!";
 27             return Content(str);
 28         }
 29 
 30         /// <summary>
 31         /// EmptyResult的用法(返回空對象)
 32         /// http://localhost:30735/home/EmptyResultDemo
 33         /// </summary>
 34         /// <returns>返回一個空對象</returns>
 35         public ActionResult EmptyResultDemo (){
 36             return new EmptyResult();
 37         }
 38 
 39         /// <summary>
 40         /// FileContentResult的用法(返回圖片)
 41         /// http://localhost:30735/home/FileContentResultDemo
 42         /// </summary>
 43         /// <returns>顯示一個文件內容</returns>
 44         public ActionResult FileContentResultDemo() {
 45             FileStream fs = new FileStream(Server.MapPath(@"/Images/001.jpg"), FileMode.Open, FileAccess.Read);
 46             byte[] buffer = new byte[Convert.ToInt32(fs.Length)];
 47             fs.Read(buffer, 0, Convert.ToInt32(fs.Length));
 48             string contentType = "image/jpeg";
 49             return File(buffer, contentType);
 50         }
 51       
 52         /// <summary>
 53         /// FilePathResult的用法(返回圖片)
 54         /// http://localhost:30735/home/FilePathResultDemo/002
 55         /// </summary>
 56         /// <param name="id">圖片id</param>
 57         /// <returns>直接將返回一個文件對象</returns>
 58         public FilePathResult FilePathResultDemo(string id)
 59         {
 60             string path = Server.MapPath(@"/Images/"+id +".jpg");
 61             //定義內容類型(圖片)
 62             string contentType = "image/jpeg";
 63             //FilePathResult直接返回file對象
 64             return File(path, contentType);
 65         }
 66 
 67         /// <summary>
 68         /// FileStreamResult的用法(返回圖片)
 69         /// http://localhost:30735/home/FileStreamResultDemo
 70         /// </summary>
 71         /// <returns>返迴文件流(圖片)</returns>
 72         public ActionResult FileStreamResultDemo()
 73         {
 74             FileStream fs = new FileStream(Server.MapPath(@"/Images/001.jpg"), FileMode.Open, FileAccess.Read);
 75             string contentType = "image/jpeg";
 76             return File(fs, contentType);
 77         }
 78 
 79         /// <summary>
 80         /// HttpUnauthorizedResult 的用法(拋出401錯誤)
 81         /// http://localhost:30735/home/HttpUnauthorizedResult
 82         /// </summary>
 83         /// <returns></returns>
 84         public ActionResult HttpUnauthorizedResultDemo()
 85         {
 86             return new HttpUnauthorizedResult();
 87         }
 88 
 89         /// <summary>
 90         /// HttpStatusCodeResult的方法(返回錯誤狀態信息)
 91         ///  http://localhost:30735/home/HttpStatusCodeResult
 92         /// </summary>
 93         /// <returns></returns>
 94         public ActionResult HttpStatusCodeResultDemo() {
 95             return new HttpStatusCodeResult(500, "System Error");
 96         }
 97 
 98         /// <summary>
 99         /// HttpNotFoundResult的使用方法
100         /// http://localhost:30735/home/HttpNotFoundResultDemo
101         /// </summary>
102         /// <returns></returns>
103         public ActionResult HttpNotFoundResultDemo() {
104             return new HttpNotFoundResult("not found action");
105         }
106 
107        /// <summary>
108        /// JavaScriptResult 的用法(返回腳本文件)
109         /// http://localhost:30735/home/JavaScriptResultDemo
110        /// </summary>
111        /// <returns>返回腳本內容</returns>
112         public ActionResult JavaScriptResultDemo()
113         {
114             return JavaScript(@"<script>alert('Test JavaScriptResultDemo!')</script>");
115         }
116 
117         /// <summary>
118         /// JsonResult的用法(返回一個json對象)
119         /// http://localhost:30735/home/JsonResultDemo
120         /// </summary>
121         /// <returns>返回一個json對象</returns>
122         public ActionResult JsonResultDemo()
123         {
124             var tempObj = new { Controller = "HomeController", Action = "JsonResultDemo" };
125             return Json(tempObj);
126         }
127 
128         /// <summary>
129         /// RedirectResult的用法(跳轉url地址)
130         /// http://localhost:30735/home/RedirectResultDemo
131         /// </summary>
132         /// <returns></returns>
133         public ActionResult RedirectResultDemo()
134         {
135             return Redirect(@"http://wwww.baidu.com");
136         }
137 
138         /// <summary>
139         /// RedirectToRouteResult的用法(跳轉的action名稱)
140         /// http://localhost:30735/home/RedirectToRouteResultDemo
141         /// </summary>
142         /// <returns></returns>
143         public ActionResult RedirectToRouteResultDemo()
144         {
145             return RedirectToAction(@"FileStreamResultDemo");
146         }
147 
148         /// <summary>
149         /// PartialViewResult的用法(返回部分視圖)
150         /// http://localhost:30735/home/PartialViewResultDemo
151         /// </summary>
152         /// <returns></returns>
153         public PartialViewResult PartialViewResultDemo()
154         {
155             return PartialView();
156         }
157 
158        /// <summary>
159        /// ViewResult的用法(返回視圖)
160         ///  http://localhost:30735/home/ViewResultDemo
161        /// </summary>
162        /// <returns></returns>
163         public ActionResult ViewResultDemo()
164         {
165             //如果沒有傳入View名稱, 預設尋找與Action名稱相同的View頁面.
166             return View();
167         }
168     }
169 }

 

 

 文章轉載自:https://www.cnblogs.com/xielong/p/5940535.html


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

-Advertisement-
Play Games
更多相關文章
  • 跨域通俗理解就是兩個功能變數名稱後面的web服務地址,即都是獨立的網站。現實業務的情況會有很多需要跨域推送數據的情況, 比如類似餓了麽商戶後臺會收到客戶端確認訂單後,後臺服務會推送一條訂單消息給商戶前臺。 Signalr跨域代碼: 前臺js代碼: 1 /** 2 獲取後臺Signalr服務地址,綁定$.co ...
  • 4. 相容舊版本 FDS最常見的問題之一是如何與Fall Creators Update之前的版本相容,其實做起來也挺簡單的, "ColorfulBox" 就實現了Creators Update與Fall Creators Update之間的相容。 4.1 使用HamburgerMenu代替Navi ...
  • 現在網站基本都用手機註冊,很少用郵箱註冊,本篇內容比較多,代碼我會儘量加備註,有些操作需要連續添加幾個文件才不報錯,如果VS顯示錯誤,請繼續後續步驟。 前面已經有一篇文章講到集成簡訊發送模塊:http://www.cnblogs.com/shensigzs/category/1147235.html ...
  • 本篇開始進入重頭戲,之前的幾篇文章都是為了現在的功能作准備。前面教程已經講到修改User表結構,接下來就需要修改註冊邏輯代碼。 註冊頁面 修改Register.cshtml,備註如下代碼: 文件路徑:D:\abp version\aspnet-zero-3.4.0\aspnet-zero-3.4.0 ...
  • 進入 迅雷開發者中心 下載最新SDK與解碼庫 註:解壓最新SDK,運行install.bat。 解壓完美解碼庫將codecs文件拷貝到項目Debug下 轉載https://www.cnblogs.com/yanjinhua/ ...
  • 之前一起吃飯聽說了發票助手這個東西,可以生成發票抬頭的二維碼,掃碼就可以開票了。 官方也有個小程式的 【稅務發票助手】,微信中搜這個名字就可以了。 我準備在自己的小程式中也嘗試一下,本來覺得只要拼接一下生成二維碼就好了,結果發現不少坑。 具體的文檔參照github上的 "便捷開票二維碼應用規範.pd ...
  • 本文主要記錄.net Core項目發佈在Linux伺服器上面所遇到的問題,防止遺忘是 1、在發佈文件中執行 dotnet xxxxxx.dll的時候提示如下錯誤: An assembly specified in the application dependencies manifest (xxx. ...
  • 一般看到的 AppBarButton 都是圖片在上面,文字在下麵,是否可以更改讓文字在和圖片相同的位置?本文告訴大家如何做出橫向的 AppBarButton 把圖標和文本放在一起。 ...
一周排行
    -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.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...