详解ASP.NET MVC的整个生命周期(2)

经过了路由模块,生成了 RouteData 路由数据,它包含了根据路由规则匹配的 Controller 和 Action。有了路由数据,需要有处理器来处理请求,这个任务就交给了 RouteData 的 RouteHandler 属性,它的类型是 IRouteHandler,它的值就是MvcRouteHandler,MvcRouteHandler 调用 GetHttpHandler 获取处理请求的 IHttpHandler 对象,在 MVC 框架中就是 MvcHandler,详细代码如下:

namespace System.Web.Mvc { /// <summary>Selects the controller that will handle an HTTP request.</summary> public class MvcHandler : IHttpAsyncHandler, IHttpHandler, IRequiresSessionState { private struct ProcessRequestState { internal IAsyncController AsyncController; internal IControllerFactory Factory; internal RequestContext RequestContext; internal void ReleaseController() { this.Factory.ReleaseController(this.AsyncController); } } [CompilerGenerated] [Serializable] private sealed class <>c { public static readonly MvcHandler.<>c <>9 = new MvcHandler.<>c(); public static BeginInvokeDelegate<MvcHandler.ProcessRequestState> <>9__20_0; public static EndInvokeVoidDelegate<MvcHandler.ProcessRequestState> <>9__20_1; public static Func<KeyValuePair<string, object>, bool> <>9__26_0; internal IAsyncResult <BeginProcessRequest>b__20_0(AsyncCallback asyncCallback, object asyncState, MvcHandler.ProcessRequestState innerState) { IAsyncResult result; try { result = innerState.AsyncController.BeginExecute(innerState.RequestContext, asyncCallback, asyncState); } catch { innerState.ReleaseController(); throw; } return result; } internal void <BeginProcessRequest>b__20_1(IAsyncResult asyncResult, MvcHandler.ProcessRequestState innerState) { try { innerState.AsyncController.EndExecute(asyncResult); } finally { innerState.ReleaseController(); } } internal bool <RemoveOptionalRoutingParameters>b__26_0(KeyValuePair<string, object> entry) { return entry.Value == UrlParameter.Optional; } } private static readonly object _processRequestTag = new object(); internal static readonly string MvcVersion = MvcHandler.GetMvcVersionString(); /// <summary>Contains the header name of the ASP.NET MVC version.</summary> public static readonly string MvcVersionHeaderName = "X-AspNetMvc-Version"; private ControllerBuilder _controllerBuilder; internal ControllerBuilder ControllerBuilder { get { if (this._controllerBuilder == null) { this._controllerBuilder = ControllerBuilder.Current; } return this._controllerBuilder; } set { this._controllerBuilder = value; } } /// <summary>Gets or sets a value that indicates whether the MVC response header is disabled.</summary> /// <returns>true if the MVC response header is disabled; otherwise, false.</returns> public static bool DisableMvcResponseHeader { get; set; } /// <summary>Gets a value that indicates whether another request can use the <see cref="T:System.Web.IHttpHandler" /> instance.</summary> /// <returns>true if the <see cref="T:System.Web.IHttpHandler" /> instance is reusable; otherwise, false.</returns> protected virtual bool IsReusable { get { return false; } } /// <summary>Gets the request context.</summary> /// <returns>The request context.</returns> public RequestContext RequestContext { get; private set; } /// <summary>Gets a value that indicates whether another request can use the <see cref="T:System.Web.IHttpHandler" /> instance.</summary> /// <returns>true if the <see cref="T:System.Web.IHttpHandler" /> instance is reusable; otherwise, false.</returns> bool IHttpHandler.IsReusable { get { return this.IsReusable; } } /// <summary>Initializes a new instance of the <see cref="T:System.Web.Mvc.MvcHandler" /> class.</summary> /// <param>The request context.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref /> parameter is null.</exception> public MvcHandler(RequestContext requestContext) { if (requestContext == null) { throw new ArgumentNullException("requestContext"); } this.RequestContext = requestContext; } /// <summary>Adds the version header by using the specified HTTP context.</summary> /// <param>The HTTP context.</param> protected internal virtual void AddVersionHeader(HttpContextBase httpContext) { if (!MvcHandler.DisableMvcResponseHeader) { httpContext.Response.AppendHeader(MvcHandler.MvcVersionHeaderName, MvcHandler.MvcVersion); } } /// <summary>Called by ASP.NET to begin asynchronous request processing.</summary> /// <returns>The status of the asynchronous call.</returns> /// <param>The HTTP context.</param> /// <param>The asynchronous callback method.</param> /// <param>The state of the asynchronous object.</param> protected virtual IAsyncResult BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, object state) { HttpContextBase httpContext2 = new HttpContextWrapper(httpContext); return this.BeginProcessRequest(httpContext2, callback, state); } /// <summary>Called by ASP.NET to begin asynchronous request processing using the base HTTP context.</summary> /// <returns>The status of the asynchronous call.</returns> /// <param>The HTTP context.</param> /// <param>The asynchronous callback method.</param> /// <param>The state of the asynchronous object.</param> protected internal virtual IAsyncResult BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, object state) { IController controller; IControllerFactory factory; this.ProcessRequestInit(httpContext, out controller, out factory); IAsyncController asyncController = controller as IAsyncController; if (asyncController != null) { BeginInvokeDelegate<MvcHandler.ProcessRequestState> arg_51_0; if ((arg_51_0 = MvcHandler.<>c.<>9__20_0) == null) { arg_51_0 = (MvcHandler.<>c.<>9__20_0 = new BeginInvokeDelegate<MvcHandler.ProcessRequestState>(MvcHandler.<>c.<>9.<BeginProcessRequest>b__20_0)); } BeginInvokeDelegate<MvcHandler.ProcessRequestState> beginDelegate = arg_51_0; EndInvokeVoidDelegate<MvcHandler.ProcessRequestState> arg_71_0; if ((arg_71_0 = MvcHandler.<>c.<>9__20_1) == null) { arg_71_0 = (MvcHandler.<>c.<>9__20_1 = new EndInvokeVoidDelegate<MvcHandler.ProcessRequestState>(MvcHandler.<>c.<>9.<BeginProcessRequest>b__20_1)); } EndInvokeVoidDelegate<MvcHandler.ProcessRequestState> endDelegate = arg_71_0; MvcHandler.ProcessRequestState invokeState = new MvcHandler.ProcessRequestState { AsyncController = asyncController, Factory = factory, RequestContext = this.RequestContext }; SynchronizationContext synchronizationContext = SynchronizationContextUtil.GetSynchronizationContext(); return AsyncResultWrapper.Begin<MvcHandler.ProcessRequestState>(callback, state, beginDelegate, endDelegate, invokeState, MvcHandler._processRequestTag, -1, synchronizationContext); } Action action = delegate { try { controller.Execute(this.RequestContext); } finally { factory.ReleaseController(controller); } }; return AsyncResultWrapper.BeginSynchronous(callback, state, action, MvcHandler._processRequestTag); } /// <summary>Called by ASP.NET when asynchronous request processing has ended.</summary> /// <param>The asynchronous result.</param> protected internal virtual void EndProcessRequest(IAsyncResult asyncResult) { AsyncResultWrapper.End(asyncResult, MvcHandler._processRequestTag); } private static string GetMvcVersionString() { return new AssemblyName(typeof(MvcHandler).Assembly.FullName).Version.ToString(2); } /// <summary>Processes the request by using the specified HTTP request context.</summary> /// <param>The HTTP context.</param> protected virtual void ProcessRequest(HttpContext httpContext) { HttpContextBase httpContext2 = new HttpContextWrapper(httpContext); this.ProcessRequest(httpContext2); } /// <summary>Processes the request by using the specified base HTTP request context.</summary> /// <param>The HTTP context.</param> protected internal virtual void ProcessRequest(HttpContextBase httpContext) { IController controller; IControllerFactory controllerFactory; this.ProcessRequestInit(httpContext, out controller, out controllerFactory); try { controller.Execute(this.RequestContext); } finally { controllerFactory.ReleaseController(controller); } } private void ProcessRequestInit(HttpContextBase httpContext, out IController controller, out IControllerFactory factory) { HttpContext current = HttpContext.Current; if (current != null) { bool? flag = ValidationUtility.IsValidationEnabled(current); bool flag2 = true; if (flag.GetValueOrDefault() == flag2 & flag.HasValue) { ValidationUtility.EnableDynamicValidation(current); } } this.AddVersionHeader(httpContext); this.RemoveOptionalRoutingParameters(); string requiredString = this.RequestContext.RouteData.GetRequiredString("controller"); factory = this.ControllerBuilder.GetControllerFactory(); controller = factory.CreateController(this.RequestContext, requiredString); if (controller == null) { throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, MvcResources.ControllerBuilder_FactoryReturnedNull, new object[] { factory.GetType(), requiredString })); } } private void RemoveOptionalRoutingParameters() { IDictionary<string, object> arg_2F_0 = this.RequestContext.RouteData.Values; Func<KeyValuePair<string, object>, bool> arg_2F_1; if ((arg_2F_1 = MvcHandler.<>c.<>9__26_0) == null) { arg_2F_1 = (MvcHandler.<>c.<>9__26_0 = new Func<KeyValuePair<string, object>, bool>(MvcHandler.<>c.<>9.<RemoveOptionalRoutingParameters>b__26_0)); } arg_2F_0.RemoveFromDictionary(arg_2F_1); } /// <summary>Enables processing of HTTP Web requests by a custom HTTP handler that implements the <see cref="T:System.Web.IHttpHandler" /> interface.</summary> /// <param>An <see cref="T:System.Web.HttpContext" /> object that provides references to the intrinsic server objects (for example, Request, Response, Session, and Server) that are used to service HTTP requests.</param> void IHttpHandler.ProcessRequest(HttpContext httpContext) { this.ProcessRequest(httpContext); } /// <summary>Called by ASP.NET to begin asynchronous request processing using the base HTTP context.</summary> /// <returns>The status of the asynchronous call.</returns> /// <param>The HTTP context.</param> /// <param>The asynchronous callback method.</param> /// <param>The data.</param> IAsyncResult IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData) { return this.BeginProcessRequest(context, cb, extraData); } /// <summary>Called by ASP.NET when asynchronous request processing has ended.</summary> /// <param>The asynchronous result.</param> void IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) { this.EndProcessRequest(result); } } } HttpRuntime 调用 IHttpHandler 类型的调用 ProcessRequest() 方法,用于处理请求。 protected internal virtual void ProcessRequest(HttpContextBase httpContext) { IController controller; IControllerFactory controllerFactory; this.ProcessRequestInit(httpContext, out controller, out controllerFactory);创建 IControllerFactory,并创建 IController 对象。 try { controller.Execute(this.RequestContext);执行Controller,背后就是调用相应的 Action 方法。 } finally { controllerFactory.ReleaseController(controller); } }

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zysfgd.html