從上一章中我們知道Http的任何一個請求最終一定是由某一個具體的HttpHandler來處理的,不管是成功還是失敗。
而具體是由哪一個HttpHandler來處理,則是由我們的配置文件來指定映射關系:后綴名與處理程序的關系(IHttpHandler---IHttpHandlerFactory) 。
但是我們都知道在MVC中訪問時並沒有使用什么后綴,而是使用路由去匹配,那這又是怎么回事呢?接下來我們就來談談這件事。
首先我們來看下MVC中到底是由哪個HttpHandler來處理的:
Home 控制器:
public class HomeController : Controller { public ActionResult Index() { ViewBag.CurrentHandler = base.HttpContext.CurrentHandler; return View(); } }
對應的 Index 視圖:
@{ ViewBag.Title = "Home Page"; } <h2> This is Home/Index View </h2> <h1> @(ViewBag.CurrentHandler) </h1> <hr />
看看此時 HttpContext.CurrentHandler 的輸出結果:

可以看到MVC中使用的HttpHandler是叫【System.Web.Mvc.MvcHandler】。
所謂MVC框架,其實就是在Asp.Net管道上擴展的,在PostResolveRequestCache事件擴展了UrlRoutingModule。
會在任何請求進來后,先進行路由匹配,如果匹配上了就指定HttpHandler為MvcHandler,沒有匹配上就還是走原始流程。
那為什么要選擇在PostResolveRequestCache這個事件進行擴展呢?

從圖中我們可以得知在PostResolveRequestCache事件之后就要指定請求該如何處理了,因此我們也就能理解為什么要選擇在PostResolveRequestCache這個事件上面進行MVC擴展了。
下面我們通過反編譯工具來看一下 UrlRoutingModule 這個類:
using System; using System.Globalization; using System.Runtime.CompilerServices; using System.Web.Security; namespace System.Web.Routing { [TypeForwardedFrom("System.Web.Routing, Version=3.5.0.0, Culture=Neutral, PublicKeyToken=31bf3856ad364e35")] public class UrlRoutingModule : IHttpModule { private static readonly object _contextKey = new object(); private static readonly object _requestDataKey = new object(); private RouteCollection _routeCollection; public RouteCollection RouteCollection { get { if (this._routeCollection == null) { this._routeCollection = RouteTable.Routes; } return this._routeCollection; } set { this._routeCollection = value; } } protected virtual void Dispose() { } protected virtual void Init(HttpApplication application) { if (application.Context.Items[UrlRoutingModule._contextKey] != null) { return; } application.Context.Items[UrlRoutingModule._contextKey] = UrlRoutingModule._contextKey; application.PostResolveRequestCache += new EventHandler(this.OnApplicationPostResolveRequestCache); } private void OnApplicationPostResolveRequestCache(object sender, EventArgs e) { HttpApplication httpApplication = (HttpApplication)sender; HttpContextBase context = new HttpContextWrapper(httpApplication.Context); this.PostResolveRequestCache(context); } [Obsolete("This method is obsolete. Override the Init method to use the PostMapRequestHandler event.")] public virtual void PostMapRequestHandler(HttpContextBase context) { } public virtual void PostResolveRequestCache(HttpContextBase context) { RouteData routeData = this.RouteCollection.GetRouteData(context); if (routeData == null) { return; } IRouteHandler routeHandler = routeData.RouteHandler; if (routeHandler == null) { throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, SR.GetString("UrlRoutingModule_NoRouteHandler"), new object[0])); } if (routeHandler is StopRoutingHandler) { return; } RequestContext requestContext = new RequestContext(context, routeData); context.Request.RequestContext = requestContext; IHttpHandler httpHandler = routeHandler.GetHttpHandler(requestContext); if (httpHandler == null) { throw new InvalidOperationException(string.Format(CultureInfo.CurrentUICulture, SR.GetString("UrlRoutingModule_NoHttpHandler"), new object[] { routeHandler.GetType() })); } if (!(httpHandler is UrlAuthFailureHandler)) { context.RemapHandler(httpHandler); return; } if (FormsAuthenticationModule.FormsAuthRequired) { UrlAuthorizationModule.ReportUrlAuthorizationFailure(HttpContext.Current, this); return; } throw new HttpException(401, SR.GetString("Assess_Denied_Description3")); } void IHttpModule.Dispose() { this.Dispose(); } void IHttpModule.Init(HttpApplication application) { this.Init(application); } } }
從上面的源碼中我們大概可以知道:
1、首先它是根據HttpContextBase從RouteCollection中獲取RouteData,判斷RouteData是否為空(也就是判斷路由是否匹配上),如果路由匹配失敗則還是走原始的Asp.Net流程,否則就走MVC流程。從中可以知道MVC和WebForm是可以共存的。也能解釋為啥指定后綴請求需要路由的忽略。
2、經過路由匹配得到RouteData,然后使用RouteData獲取RouteHandler,接着再根據RouteHandler獲取HttpHandler,最后將HttpContextBase上下文中的HttpHandler指定為這個HttpHandler。
3、看完下文你就會知道從RouteCollection中獲取的這個RouteHandler其實就是MvcRouteHandler,而最終獲取到的這個HttpHandler其實就是MvcHandler。
我們繼續通過反編譯工具 沿着 this.RouteCollection.GetRouteData(context) 往里找:
// System.Web.Routing.RouteCollection public RouteData GetRouteData(HttpContextBase httpContext) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } if (httpContext.Request == null) { throw new ArgumentException(SR.GetString("RouteTable_ContextMissingRequest"), "httpContext"); } if (base.Count == 0) { return null; } bool flag = false; bool flag2 = false; if (!this.RouteExistingFiles) { flag = this.IsRouteToExistingFile(httpContext); flag2 = true; if (flag) { return null; } } using (this.GetReadLock()) { foreach (RouteBase current in this) { RouteData routeData = current.GetRouteData(httpContext); if (routeData != null) { RouteData result; if (!current.RouteExistingFiles) { if (!flag2) { flag = this.IsRouteToExistingFile(httpContext); } if (flag) { result = null; return result; } } result = routeData; return result; } } } return null; }
從此處我們可以發現,它是按照添加順序進行匹配的,第一個吻合的就直接返回,后面的無效。
說到RouteCollection其實我們並不陌生,在路由配置的時候就有用到它:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; namespace AspNetPipeline { /// <summary> /// 路由是按照注冊順序進行匹配,遇到第一個吻合的就結束匹配,每個請求只會被一個路由匹配上。 /// </summary> public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { //忽略路由 正則表達式 {resource}表示變量 a.axd/xxxx resource=a pathInfo=xxxx //.axd是歷史原因,最開始都是WebForm,請求都是.aspx后綴,IIS根據后綴轉發請求; //MVC出現了,沒有后綴,IIS6以及更早版本,打了個補丁,把MVC的請求加上個.axd的后綴,然后這種都轉發到網站 //新版本的IIS已經不需要了,遇到了就直接忽略,還是走原始流程 routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); //該行框架自帶的 //.log后綴的請求忽略掉,不走MVC流程,而是用我們自定義的CustomHttpHandler處理器來處理 routes.IgnoreRoute("{resource}.log/{*pathInfo}"); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); } } }
我們將光標移動到MapRoute這個方法,然后按F12查看源碼,可以發現它是來自 RouteCollectionExtensions 這個擴展類,如下所示:

我們通過反編譯工具找到這個類:

我們重點關注其中的MapRoute方法:
/// <summary>Maps the specified URL route and sets default route values, constraints, and namespaces.</summary> /// <returns>A reference to the mapped route.</returns> /// <param name="routes">A collection of routes for the application.</param> /// <param name="name">The name of the route to map.</param> /// <param name="url">The URL pattern for the route.</param> /// <param name="defaults">An object that contains default route values.</param> /// <param name="constraints">A set of expressions that specify values for the <paramref name="url" /> parameter.</param> /// <param name="namespaces">A set of namespaces for the application.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="routes" /> or <paramref name="url" /> parameter is null.</exception> 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 = RouteCollectionExtensions.CreateRouteValueDictionaryUncached(defaults), Constraints = RouteCollectionExtensions.CreateRouteValueDictionaryUncached(constraints), DataTokens = new RouteValueDictionary() }; ConstraintValidation.Validate(route); if (namespaces != null && namespaces.Length != 0) { route.DataTokens["Namespaces"] = namespaces; } routes.Add(name, route); return route; } private static RouteValueDictionary CreateRouteValueDictionaryUncached(object values) { IDictionary<string, object> dictionary = values as IDictionary<string, object>; if (dictionary != null) { return new RouteValueDictionary(dictionary); } return TypeHelper.ObjectToDictionaryUncached(values); }
可以看到RouteCollection字典容器的key就是路由配置中的name,這也就解釋了路由配置中的name為啥需要唯一,另外RouteCollection字典容器的value存的是Route對象(正則規則 + MvcRouteHandler + 其它路由配置信息)。
我們繼續通過反編譯工具找到 MvcRouteHandler,如下所示:
using System; using System.Web.Mvc.Properties; using System.Web.Routing; using System.Web.SessionState; namespace System.Web.Mvc { /// <summary>Creates an object that implements the IHttpHandler interface and passes the request context to it.</summary> public class MvcRouteHandler : IRouteHandler { private IControllerFactory _controllerFactory; /// <summary>Initializes a new instance of the <see cref="T:System.Web.Mvc.MvcRouteHandler" /> class.</summary> public MvcRouteHandler() { } /// <summary>Initializes a new instance of the <see cref="T:System.Web.Mvc.MvcRouteHandler" /> class using the specified factory controller object.</summary> /// <param name="controllerFactory">The controller factory.</param> public MvcRouteHandler(IControllerFactory controllerFactory) { this._controllerFactory = controllerFactory; } /// <summary>Returns the HTTP handler by using the specified HTTP context.</summary> /// <returns>The HTTP handler.</returns> /// <param name="requestContext">The request context.</param> protected virtual IHttpHandler GetHttpHandler(RequestContext requestContext) { requestContext.HttpContext.SetSessionStateBehavior(this.GetSessionStateBehavior(requestContext)); return new MvcHandler(requestContext); } /// <summary>Returns the session behavior.</summary> /// <returns>The session behavior.</returns> /// <param name="requestContext">The request context.</param> protected virtual SessionStateBehavior GetSessionStateBehavior(RequestContext requestContext) { string text = (string)requestContext.RouteData.Values["controller"]; if (string.IsNullOrWhiteSpace(text)) { throw new InvalidOperationException(MvcResources.MvcRouteHandler_RouteValuesHasNoController); } return (this._controllerFactory ?? ControllerBuilder.Current.GetControllerFactory()).GetControllerSessionBehavior(requestContext, text); } /// <summary>Returns the HTTP handler by using the specified request context.</summary> /// <returns>The HTTP handler.</returns> /// <param name="requestContext">The request context.</param> IHttpHandler IRouteHandler.GetHttpHandler(RequestContext requestContext) { return this.GetHttpHandler(requestContext); } } }
找到其中關鍵方法:

可以發現這個方法的返回值是固定寫死的,就是返回MvcHandler的一個實例。由此我們知道從RouteCollection中獲取的HttpHandler其實就是MvcHandler。
至此,我們對MVC的處理流程應該就有個大概認識了,下面我們通過一張圖來總結一下MVC的處理流程:

既然原理我們都知道了,那下面我們就可以去做一些有用的擴展。
例如:擴展我們的路由。
從上文中我們知道,路由配置其實就是將Route對象添加到RouteCollection字典中,而從反編譯工具中我們可以得知Route的基類是RouteBase:

那下面我們就來自定義一個Route:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; namespace AspNetPipeline.RouteExtend { /// <summary> /// 自定義路由 /// </summary> public class CustomRoute : RouteBase { /// <summary> /// 如果是 Chrome/74.0.3729.169 版本,允許正常訪問,否則跳轉提示頁 /// </summary> /// <param name="httpContext"></param> /// <returns></returns> public override RouteData GetRouteData(HttpContextBase httpContext) { //httpContext.Request.Url.AbsoluteUri if (httpContext.Request.UserAgent.Contains("Chrome/74.0.3729.169")) { return null; //繼續后面的 } else { RouteData routeData = new RouteData(this, new MvcRouteHandler()); //還是走MVC流程 routeData.Values.Add("controller", "home"); routeData.Values.Add("action", "refuse"); return routeData; //中斷路由匹配 } } public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values) { return null; } } }
然后將其添加到RouteCollection字典中:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; using AspNetPipeline.RouteExtend; namespace AspNetPipeline { /// <summary> /// 路由是按照注冊順序進行匹配,遇到第一個吻合的就結束匹配,每個請求只會被一個路由匹配上。 /// </summary> public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { //忽略路由 正則表達式 {resource}表示變量 a.axd/xxxx resource=a pathInfo=xxxx //.axd是歷史原因,最開始都是WebForm,請求都是.aspx后綴,IIS根據后綴轉發請求; //MVC出現了,沒有后綴,IIS6以及更早版本,打了個補丁,把MVC的請求加上個.axd的后綴,然后這種都轉發到網站 //新版本的IIS已經不需要了,遇到了就直接忽略,還是走原始流程 routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); //該行框架自帶的 //.log后綴的請求忽略掉,不走MVC流程,而是用我們自定義的CustomHttpHandler處理器來處理 routes.IgnoreRoute("{resource}.log/{*pathInfo}"); routes.Add("chrome", new CustomRoute()); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); } } }
最后我們來訪問一下 /home/index 頁面,運行結果如下所示:

仔細觀察后你會發現我們訪問的是 /home/index 頁面,但是此時卻輸出了 /home/refuse 頁面,說明我們的路由擴展成功了。
除了去擴展Route,此外我們也可以去擴展MvcRouteHandler,如下所示:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; using AspNetPipeline.Pipeline; namespace AspNetPipeline.RouteExtend { /// <summary> /// 自定義MvcRouteHandler /// </summary> public class CustomMvcRouteHandler : MvcRouteHandler { protected override IHttpHandler GetHttpHandler(RequestContext requestContext) { //requestContext.HttpContext.SetSessionStateBehavior(this.GetSessionStateBehavior(requestContext)); //return new MvcHandler(requestContext); return new CustomHttpHandler(); //將MvcHandler替換成自定義的HttpHandler } } }
同樣的,我們將其添加到RouteCollection字典中:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; using AspNetPipeline.RouteExtend; namespace AspNetPipeline { /// <summary> /// 路由是按照注冊順序進行匹配,遇到第一個吻合的就結束匹配,每個請求只會被一個路由匹配上。 /// </summary> public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { //忽略路由 正則表達式 {resource}表示變量 a.axd/xxxx resource=a pathInfo=xxxx //.axd是歷史原因,最開始都是WebForm,請求都是.aspx后綴,IIS根據后綴轉發請求; //MVC出現了,沒有后綴,IIS6以及更早版本,打了個補丁,把MVC的請求加上個.axd的后綴,然后這種都轉發到網站 //新版本的IIS已經不需要了,遇到了就直接忽略,還是走原始流程 routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); //該行框架自帶的 //.log后綴的請求忽略掉,不走MVC流程,而是用我們自定義的CustomHttpHandler處理器來處理 routes.IgnoreRoute("{resource}.log/{*pathInfo}"); routes.Add("config", new Route("log/{*pathInfo}", new CustomMvcRouteHandler())); routes.Add("chrome", new CustomRoute()); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); } } }
最后我們來訪問下 /log/a 運行結果如下所示:

右鍵查看網頁源代碼:

可以發現輸出了我們想要的東西,說明我們的MvcRouteHandler擴展成功了。
小結:
1、擴展自己的Route,寫入RouteCollection,可以自定義規則完成路由。
2、擴展HttpHandle,就可以為所欲為,跳出MVC框架。
至此本文就全部介紹完了,如果覺得對您有所啟發請記得點個贊哦!!!
Demo源碼:
鏈接:https://pan.baidu.com/s/1Rb4uq0yB_iB3VsonwiCFKw 提取碼:68r6
此文由博主精心撰寫轉載請保留此原文鏈接:https://www.cnblogs.com/xyh9039/p/15216683.html
版權聲明:如有雷同純屬巧合,如有侵權請及時聯系本人修改,謝謝!!!
