Asp.net Mvc Framework 二 (URL Routing初解)

來源:互聯網
上載者:User

什麼是URLRouting呢?
你可以使用URL routing來配置一些URL的映射,使使用者可以按你的規則來訪問網站.
使用URL routing,一定要規定URL模式,它包括一個位置標識,它將在你請求網頁時按這個規則返回給你內容. 當然,這個建立的規則完全是由你自己定義的.

上回說道:

http://localhost/Views/Home/Index.aspx和

http://localhost/Views/Home/About.aspx並無法訪問

Views/Home/Index.aspx

Views/Home/About.aspx
這是怎麼回事呢,那我們要怎樣才能訪問呢
答案是:

http://localhost/Home和

http://localhost/Home/About

於是可能你會問了:為什麼呢?(MS很春很晚)
原因是因為頁面URL的請求規則在Global.asax.cs中定義的規則所決定

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace MvcApplication2
{
    /**//// <summary>
    /// 還是老規矩,按序號看
    /// </summary>
    public class GlobalApplication : System.Web.HttpApplication
    {
        public static void RegisterRoutes(RouteCollection routes) {
            // 4.注意: 將URL 規則更改為 "{controller}.mvc/{action}/{id}" 即可
            // 自行支援 IIS6 and IIS7 兩種模式
            // 筆者注:一般的虛擬機器主機不支援.mvc,.aspx也要檢查檔案存在
            // 所以你可以將.mvc換成.ashx或.asbx

            //1.因為MVC與傳統Aspx的最大不同就是訪問是訪問的Controller/Action
            //而不是aspx檔案,要展現給使用者哪一個aspx檔案是由Controller決定的
            //這個是檔案預設內建的URLRouting規則,是將Controller/Action/id的訪問
            //模式指向那個Controller
            routes.Add(new Route("{controller}/{action}/{id}", new MvcRouteHandler())
            {
                Defaults = new RouteValueDictionary(new { action = "Index", id = "" }),
            });
            //2.這個URL Routing是為瞭解決直接存取網域名稱時,會出現找不到檔案的情況
            //所以要採用這個方法將首頁Routing到Home/Index上,Add方法現在多用MapRoute方法替代
            routes.Add(new Route("Default.aspx", new MvcRouteHandler())
            {
                Defaults = new RouteValueDictionary(new { controller = "Home", action = "Index", id = "" }),
            });
        }

        protected void Application_Start(object sender, EventArgs e) {
            //3.這個沒什麼好講了,就是在應用程式啟動時初始化它
            RegisterRoutes(RouteTable.Routes);
        }
    }
}

注意這一點
URL只與Controller有關

URLRouting是解決傳統的
post.aspx?year=1999&month=3&day=8的參數URL變為
/post/1999/3/8/這樣的簡短漂亮且有意義的URL

以樣本中的Global.asax.cs中定義的{controller}/{action}/{id}規則為列
/Home/About/12其實就是訪問
Controller="Home" Action="About" 它的參數為 id="12"

那麼我們要怎麼利用Controller寫自己想要的頁面呢
還是老話,下回分解

 

相關:

System.Web.Routing入門及進階 上篇

System.Web.Routing入門及進階 下篇

System.Web.Routing 的說明文檔

 

 

相關文章

聯繫我們

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