ASP.NET MVC——URL路由

來源:互聯網
上載者:User

標籤:

在MVC之前,ASP.NET假設請求的URL與伺服器上的檔案之間有關聯,伺服器接受請求,並輸出相應的檔案。而在引入MVC後,請求是由控制器的動作方法來處理的。為了處理URL,便引入了路由系統。

首先我們來建立一個基礎項目用來示範。代碼如下:

1     public class HomeController : Controller2     {3         public ActionResult Index()4         {5             ViewBag.Controller = "Home";6             ViewBag.Action = "Index";7             return View("ActionName");8         }
}
1     public class AdminController : Controller2     {3         public ActionResult Index()4         {5             ViewBag.Controller = "Admin";6             ViewBag.Action = "Index";7             return View("ActionName");8         }9     }

有兩個controller,它們都返回視圖“ActionName”,我們建立一個Shared檔案夾並在其中建立一個”ActionName“視圖,代碼如下:

@{    Layout = null;}<!DOCTYPE html><html><head>    <meta name="viewport" content="width=device-width" />    <title>ActionName</title></head><body>    <div>The controller is: @ViewBag.Controller</div>    <div>The action is: @ViewBag.Action</div></body></html>
  1. 建立並註冊一條簡單的路由

          路由是在Routefig.cs檔案中定義的,我們開啟檔案,會看到有一條預設的路由如下:

routes.MapRoute(                name: "Default",                url: "{controller}/{action}/{id}",                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }               );

我們可以刪掉這條路由,手工來建立。例如這樣:

routes.MapRoute("MyRoute", "{controller}/{action}");

我們將URL寫為localhost:連接埠/Admin/Index,我們可以看到瀏覽器成功轉到了Admin控制器的Index動作方法。

ASP.NET MVC——URL路由

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.