1. 程式人生 > >asp.net mvc之ActionResult

asp.net mvc之ActionResult

new 特殊 包含 string 工作 json數據 value orm none

Web服務器接收到一個客戶端請求以後,會對請求予以相應,而這個響應是通過Response來控制的,

但是在asp.net mvc 裏,這部分的工作是由ActionResult來完成的,

ActionResult是一個抽象類,所以具體的工作還是由很多個子類來完成,

具體的子類有

EmptyResult,

ContentResult

(通過Content,ContentEncoding,ContentType 分別設置返回的內容,字符編碼格式以及媒體類型),

FileResult(FileContentResult,FilePathResult,FileStreamResult),

<p>Use this area to provide additional information.</p>
<a href="@Url.Action("ImagePath1", new  { id="1" })">下載</a>

<img src="@Url.Action("ImagePath1", new  { id="1" })" />

<img src="@Url.Action("ImagePath", new  { id="1" })" />

<img src="@Url.Action("ImageContent", new  { id="1" })" />

<img src="@Url.Action("ImageStream", new  { id="1" })" />

        public ActionResult ImagePath(string id)
        {
            string path = Server.MapPath("/images/" + id + ".jpeg");
            return File(path, "image/jpeg");
        }

        public ActionResult ImagePath1(string id)
        {
            string path = Server.MapPath("/images/" + id + ".jpeg");
            return File(path, "image/jpeg", "下載");
        }


        public ActionResult ImageContent(string id)
        {
            string path = Server.MapPath("/images/" + id + ".jpeg");
            byte[] heByte = null;
            using (FileStream fsRead = new FileStream(path, FileMode.Open, FileAccess.Read))
            {
                int fsLen = (int)fsRead.Length;
                heByte = new byte[fsLen];
                int r = fsRead.Read(heByte, 0, heByte.Length);
            }
            return File(heByte, "image/jpeg");
        }
        public ActionResult ImageStream(string id)
        {
            string path = Server.MapPath("/images/" + id + ".jpeg");
            FileStream fsRead = new FileStream(path, FileMode.Open, FileAccess.Read);

            return File(fsRead, "image/jpeg");

        }

JavaScriptResult,

返回一段js,且媒體類型是application/x-javascript,

JsonResult,

返回Json數據,默認ContentType為Application/json.

HttpStatusCodeResult,

具體是通過設置response的StatusCode和StatusDescription來完成輸出

RedirectResult,RedirectToRouteResult,

內部是通過Response的Redirect/RedirectPermanent來完成操作,

redirectresult具有兩個屬性permanent和URL,URL可以是絕對的地址也可以是相對地址,permanent決定了重定向是暫時的還是永久的重定向,

兩種重定向的不同點事搜索引擎會根據永久重定向來更新自己的索引,

RedirectToRouteResult較RediretResult多了一步根據路由計算出來這個URL值,

所以RedirectToRouteResult沒有URL屬性,卻包含RouteName以及RouteValues屬性,

ViewResult.

ViewResult是一個特殊的ActionResult,但也是最復雜的一個

asp.net mvc之ActionResult