.net mvc每次请求时第一个执行的方法是?在那个具体类里面?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了.net mvc每次请求时第一个执行的方法是?在那个具体类里面?相关的知识,希望对你有一定的参考价值。

当我们对ASP.NET MVC应用程序发起请求的时候,请求会被UrlRoutingModule HTTP Module拦截。HTTP Module是特殊类型的类,它参与每一次页面请求。
以上人CSDN上说的,但是找不着具体的类,为什么?

事实上,楼上的回答并不准确。

以下是我的个人的理解,它基于MSDN及《Apress.Pro.ASP.NET.MVC.2.Framework.2nd.Edition.Jun.2010》。

请求经过IIS之后,不管是经aspnet_isapi.dll引用(经典模式下)还是IIS自己引用(IIS7.x集成模式下),第一个被引用的是UrlRoutingModule类的实例。此类唯一的属性是RouteCollection(相信你已经知道它是什么了)。
UrlRoutingModule类里有一个Init()方法,此方法的修饰符、返回值跟签名如下
protected virtual void Init(
HttpApplication application
)
根据MSDN提供的说明,此方法做的应该是根据HttpApplication的Context等属性构造请求处理过程所必需的数据结构,如HttpContext等。
在UrlRoutingModule类里还有一个叫PostResolveRequestCache()的方法,这个方法根据Init()方法所获得的请求信息迭代RouteCollection,直到找到匹配的Route项,PostResolveRequestCache()方法便实例化一个MvcRouteHandler(这个就是楼上所说的东东,此类实现接口IRouteHandler)实例。

获得MvcRouteHandler后,UrlRoutingModule再从此MvcRouteHandler实例里获得另一个类MvcHandler(此类实现接口IHttpAsyncHandler, IHttpHandler, IRequiresSessionState)的实例,这个实例便能根据请求信息获得需要的controller工厂(默认的是DefaultControllerFactory),而此工厂根据路由信息生产一个controller。

然后就是相对熟悉的controller/action了。。

如果不明白的话,请补充问题,希望我能帮到你。
如果这对你有帮助话,请将此标为最佳答案,谢谢。
参考技术A 可以认为是MvcRouteHandler

Asp.Net MVC的路由

  通过前面几篇博文的介绍,现在我们已经清楚了asp.net请求管道是怎么一回事了,这篇博文来聊聊MVC的路由。

  其实MVC的请求管道和Asp.Net请求管道一样,只是MVC扩展了UrlRoutingModule的动作。我们知道MVC网站启动后第一个请求会执行Global.asax文件中的Application_Start方法,完成一些初始化工作,其中就会注册路由,先来看下面一张图,该图可以直观的展示了MVC执行的流程。

技术图片技术图片

   结合上图,我们一起来看看代码是如何实现路由的注册的。

 protected void Application_Start()
 
      AreaRegistration.RegisterAllAreas();
      RouteConfig.RegisterRoutes(RouteTable.Routes);
 

 public class RouteConfig
 
     public static void RegisterRoutes(RouteCollection routes)
     
        routes.IgnoreRoute("resource.axd/*pathInfo");

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

RouteCollection通过MapRoute扩展方法拿着Url来创建Route并注册到RouteCollection其中,这一点我们通过源码可以看到该方法是如何操作的,该方法通过new一个MvcRouteHandler来创建Route。MvcRouteHandler创建了MvcHandler。紧接着继续往下执行,创建HttpApplication实例,执行后续事件,在PostResolveRequestCache事件去注册UrlRouteModule的动作。

// System.Web.Mvc.RouteCollectionExtensions
/// <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;
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);
            
            IControllerFactory controllerFactory = this._controllerFactory ?? ControllerBuilder.Current.GetControllerFactory();
            return controllerFactory.GetControllerSessionBehavior(requestContext, text);
        
        IHttpHandler IRouteHandler.GetHttpHandler(RequestContext requestContext)
        
            return this.GetHttpHandler(requestContext);
        
    
using System;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Web.Security;
namespace System.Web.Routing

    /// <summary>Matches a URL request to a defined route.</summary>
    [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;
        /// <summary>Gets or sets the collection of defined routes for the ASP.NET application.</summary>
        /// <returns>An object that contains the routes.</returns>
        public RouteCollection RouteCollection
        
            get
            
                if (this._routeCollection == null)
                
                    this._routeCollection = RouteTable.Routes;
                
                return this._routeCollection;
            
            set
            
                this._routeCollection = value;
            
        
        /// <summary>Disposes of the resources (other than memory) that are used by the module.</summary>
        protected virtual void Dispose()
        
        
        /// <summary>Initializes a module and prepares it to handle requests.</summary>
        /// <param name="application">An object that provides access to the methods, properties, and events common to all application objects in an ASP.NET application.</param>
        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);
        
        /// <summary>Assigns the HTTP handler for the current request to the context.</summary>
        /// <param name="context">Encapsulates all HTTP-specific information about an individual HTTP request.</param>
        /// <exception cref="T:System.InvalidOperationException">The <see cref="P:System.Web.Routing.RouteData.RouteHandler" /> property for the route is null.</exception>
        [Obsolete("This method is obsolete. Override the Init method to use the PostMapRequestHandler event.")]
        public virtual void PostMapRequestHandler(HttpContextBase context)
        
        
        /// <summary>Matches the HTTP request to a route, retrieves the handler for that route, and sets the handler as the HTTP handler for the current request.</summary>
        /// <param name="context">Encapsulates all HTTP-specific information about an individual HTTP request.</param>
        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);
        
    

  到此,路由的注册动作也就告一段落。那么在理解了MVC的路由后,可以做什么呢?我们可以对路由做一些我们自己的扩展。

  可以从三个层面来扩展路由:

  一、在MapRoute范围内进行扩展,这种扩展只是在扩展正则表达式

 public static void RegisterRoutes(RouteCollection routes)
        
            routes.IgnoreRoute("resource.axd/*pathInfo");//忽略路由
                                                             //mvc路由规则下的扩展
            routes.IgnoreRoute("Handler/*pathInfo");
            routes.MapRoute(
             name: "About",
             url: "about",//不区分大小写
             defaults: new  controller = "First", action = "String", id = UrlParameter.Optional 
            );//静态路由
            routes.MapRoute("TestStatic", "Test/action", new  controller = "Second" );//替换控制器

            routes.MapRoute(
                    "Regex",
                     "controller/action_Year_Month_Day",
                     new  controller = "First", id = UrlParameter.Optional ,
                     new  Year = @"^\\d4", Month = @"\\d2", Day = @"\\d2" 
                       );//正则路由

            routes.MapRoute(
                name: "Default",
                url: "controller/action/id",
                defaults: new  controller = "Home", action = "Index", id = UrlParameter.Optional ,
                namespaces: new string[]  "Jesen.Web.Controllers" 
            );
          
        

 

  二、通过继承RouteBase来扩展Route,这种扩展可以随意的定制规则,而不仅仅是表达式

    /// <summary>
    /// 直接扩展route
    /// </summary>
    public class MyRoute : RouteBase
    
        /// <summary>
        /// 解析路由信息
        /// </summary>
        /// <param name="httpContext"></param>
        /// <returns></returns>
        public override RouteData GetRouteData(HttpContextBase httpContext)
        
       //此处可以根据自己的需求做一些路由的配置,例如拒绝某个浏览器的访问,检测到Chrome浏览器,则直接跳转到某个url
if (httpContext.Request.UserAgent.IndexOf("Chrome/69.0.3497.92") >= 0) RouteData rd = new RouteData(this, new MvcRouteHandler()); rd.Values.Add("controller", "Pipe"); rd.Values.Add("action", "Refuse"); return rd; return null; /// <summary> /// 指定处理的虚拟路径 /// </summary> /// <param name="requestContext"></param> /// <param name="values"></param> /// <returns></returns> public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values) return null;

接着在RouteConfig和Global.asax中注册该路由

public static void RegisterMyRoutes(RouteCollection routes)

    routes.Add(new MyRoute());


protected void Application_Start()

    RouteConfig.RegisterMyRoutes(RouteTable.Routes);

  

  三、扩展Handler,不一定是MvcHandler,可以是我们熟悉的IHttpHandler

 

    /// <summary>
    /// 扩展IRouteHandler /// </summary>
    public class MyRouteHandler : IRouteHandler
    
        public IHttpHandler GetHttpHandler(RequestContext requestContext)
        
            return new MyHttpHandler(requestContext);
        
    

    /// <summary>
    /// 扩展IHttpHandler
    /// </summary>
    public class MyHttpHandler : IHttpHandler
    
        public MyHttpHandler(RequestContext requestContext)
        
            
        

        public void ProcessRequest(HttpContext context)
        
            string url = context.Request.Url.AbsoluteUri;
            context.Response.Write((string.Format("当前地址为:0", url)));
            context.Response.End();
        

        public virtual bool IsReusable
        
            get
            
                return false;
            
        
    

RouteConfig.cs文件中配置路由

  public static void RegisterMyMVCHandler(RouteCollection routes)
  
      routes.Add(new Route("MyMVC/*Info", new MyRouteHandler()));
  

Global中注册路由

 RouteConfig.RegisterMyMVCHandler(RouteTable.Routes);

运行看结果

技术图片

 

以上是关于.net mvc每次请求时第一个执行的方法是?在那个具体类里面?的主要内容,如果未能解决你的问题,请参考以下文章

Asp.Net MVC的路由

asp.net mvc 4控制器并行执行多个ajax调用

ASP.NET MVC 控制器生命周期

ASP.NET MVC 生命周期 - 每个页面请求做一些工作

为ASP.NET MVC程序集成Autofac

ASP.NET MVC 实现AJAX跨域请求方法《1》