一、ASP.NET MVC 路由(一)--- ASP.NET WebForm路由類比

來源:互聯網
上載者:User

標籤:style   blog   http   io   color   ar   os   使用   sp   

      ASP.NET WebForm 應用,使用者請求的是物理檔案,其中包括靜態頁面和動態網頁面,在Url中的顯示都是伺服器中一個物理檔案的相對路徑。但是ASP.NET MVC就不同了,使用者請求的是Controller中一個Action方法,這種請求是通過路由將Url映射到相對的Controller和Action中。

                ASP.NET MVC是在Application_Start時,定義了路由的規則,當使用者使用規定的路由規則進行訪問時,就會通過路由映射的方式實現使用者完整的Url訪問。下面我們就開始使用Asp.net WebForm進行簡單的路由類比。

              一、我們建立一個ASP.NET Empty  Web Application

   二、添加一個Global.asax檔案,並在Application_Start事件中類比ASP.NET MVC寫路由代碼。(註:Application_Start 事件是當整個應用程式部署到IIS等伺服器,啟動應用程式集區時執行一次)

protected void Application_Start(object sender, EventArgs e){    var defaults = new RouteValueDictionary    {        {"controlls","*"},        {"action","*"}    };//定義一個路由字典    RouteTable.Routes.MapPageRoute("defaults", "{controller}/{action}", "~/RouteMapping.aspx", true, defaults);//進行預設的路由映射,在整個類比路由的過程中,所有的使用者請求都將交給RouteMapping.aspx這WebForm頁面進行處理。}

 

三、使用者請求"{controller}/{action}"格式的Url路徑,如http://localhost:1673/Abc ,那麼將顯示Abc.aspx頁面的內容。

僅僅在Application_Start中配置資訊是達不到的效果的。配置的路由資訊僅僅是映射了RouteMapping.aspx這一個頁面,要想達到較好的效果,需要對RouteMapping.as頁面擷取到的"{controller}/{action}"資訊進行稍微的處理。

protected void Page_Load(object sender, EventArgs e)        {            string controller = RouteData.Values["controller"] as String;//擷取到路由表中的controller資料            //string action = RouteData.Values["action"] as String;            if (!String.IsNullOrEmpty(controller))            {                if (controller == "*")                {                    Server.Transfer("Default.aspx");//Url地址如http://localhost:1673/則訪問預設頁                }                else                {                    try                    {                        Server.Transfer(controller + ".aspx");//使用Server.Transfer進行伺服器端重新導向,進而顯示了controller對應的頁面方法。                    }                    catch                    {                                            }                }            }        }

 


 

一、ASP.NET MVC 路由(一)--- ASP.NET WebForm路由類比

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.