MVC中ActionResult的返回值類型

本文轉載自這裏

首先咱們瞭解一下對action的要求:javascript

1.必須是一個public方法html

2.必須是實例方法java

3.不能被重載web

4.必須返回ActionResult類型json

常見的ActionResult

一、ViewResult

表示一個視圖結果,它根據視圖模板產生應答內容。對應的Controller方法爲View。服務器

二、PartialViewResult

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

三、RedirectResult

表示一個鏈接跳轉,至關於ASP.NET中的Response.Redirect方法,對應得Controller方法爲Redirect。編碼

四、RedirectToRouteResult

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

五、ContentResult

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

六、EmptyResult

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

七、JavaScriptResult

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

八、JsonResult

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

九、FileResult(FilePathResult、FileContentResult、FileStreamResult)

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

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

FileContentResult: 返回byte字節給客戶端(好比圖片)

FileStreamResult: 返回流

十、HttpUnauthorizedResult

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

十一、HttpStatusCodeResult

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

十二、HttpNoFoundResult

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

部分代碼以下:

public ActionResult ContentDemo()
{
    string str = "content";
    return Content(str);
}
public ActionResult FileDemo1()
{
    FileStream fs = new FileStream(Server.MapPath(@"/File/001.png"), FileMode.Open, FileAccess.Read);
    byte[] buffer = new byte[Convert.ToInt32(fs.Length)];
    fs.Read(buffer, 0, buffer.Length);
    string fileType = "image/png";
    return File(buffer, fileType);
}
public ActionResult fileDemo2()
{
    string path = Server.MapPath(@"/File/001.png");
    string fileType = "image/png";
    return File(path, fileType);
}
public ActionResult fileDemo3()
{
    FileStream fs = new FileStream(Server.MapPath(@"/File/001.png"), FileMode.Open, FileAccess.Read);
    string fileType = "image/png";
    return File(fs, fileType);
}
public ActionResult httpStatusCodeDemo()
{
    return new HttpStatusCodeResult(500, "System error");
}
public ActionResult javaScriptDemo()
{
    return JavaScript(@"<Script>alert('JavaScriptDemo');</Script>")
        }
public ActionResult jsonDemo()
{
    return Json("test");
}
相關文章
相關標籤/搜索