深入理解ASP.NET MVC(1)

來源:互聯網
上載者:User

 

系列目錄

ASP.NET MVC請求的服務過程

是書中的,表述了一次通常的ASP.NET MVC請求的服務過程:

可以初步看出一個HttpRequest是如何被ASP.NET和ASP.NET MVC架構執行的:經過IIS和ASP.NET處理後,Core Routing會首先根據URL匹配實體路徑上的檔案,如果不能匹配則由核心路由模組執行路由,路由被匹配後,MvcRouteHandler會將這個請求“帶入”MVC架構,執行Controller和Action,Action可以直接注入response,或者更平常的是返回一個ActionResultActionResultExecutedResult方法將被調用,如果是個ViewResult(繼承自ActionResult),則會使用WebFormViewEngine轉化一個Html,並注入到response。

在以後的系列中,將會對以上過程進行詳細分析理解。

  

URL機制包括什麼

URL映射不是MVC的機制,但是MVC充分依賴它,並發揮了它的優勢。它位於MVC架構前端,是MVC主架構的入口。傳統的URL往往對應了伺服器磁碟實體路徑的檔案,而MVC的URL機制打破了這種束縛,使得伺服器的檔案組織可以不再暴露於眾,而是映射到controller和action上。URL機制包括兩個主要的工作:

1.URL正向映射(inbound)到Controller和Action

2.Controller和Action反向映射(outbound)並構造URL

 

設定路由

先來回顧一下基本的內容。應用程式初次啟動時需要像下面這樣註冊一個URL:

routes.MapRoute(null,    "{controller}/{action}",    new { controller = "CarView", action = "Index" } );

上面代碼的MapRoute其實是RouteCollection的一個擴充方法,它有多個重載,先來看看MapRoute最複雜的一個重載版本的源碼:

public static Route MapRoute(this RouteCollection routes, string name, string url, object defaults, object constraints, string[] namespaces) {    if (routes == null) {        throw new ArgumentNullException("routes");    }    if (url == null) {        throw new ArgumentNullException("url");    }    Route route = new Route(url, new MvcRouteHandler()) {        Defaults = new RouteValueDictionary(defaults),        Constraints = new RouteValueDictionary(constraints)    };    if ((namespaces != null) && (namespaces.Length > 0)) {        route.DataTokens = new RouteValueDictionary();        route.DataTokens["Namespaces"] = namespaces;    }    routes.Add(name, route);    return route;}

從源碼可以看出,MapRoute做的事情就是構造一個Route對象,將它加到全域的RouteCollection:RouteTable.Routes中。RouteCollection是RouteBase的集合,Route對象繼承自RouteBase。先簡單看看Route對象的一些屬性:

屬性名稱 描述
Url(string) 將要被匹配的URL模型,其中用{}定義參數名
RouteHandler(IRouteHandler) 當Route匹配的時候,IRouteHandler應當處理request
Defaults(RouteValueDictionary) 為參數提供一個預設值表
Constraints(RouteValueDictionary) 為參數提供匹配規則表
DataTokens(RouteValueDictionary) 為route handler提供一個選擇controller的依據,主要用於Areas機制

這些屬性將在下面的內容中深入討論。

 

 

勞動果實,轉載請聲明出處:http://www.cnblogs.com/P_Chou/archive/2010/11/01/details-asp-net-mvc-01.html

相關文章

聯繫我們

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