asp.net原理(总结整理 2)

 

 

 

 

 

 

 

 

  1 private void ProcessRequestInternal(HttpWorkerRequest wr)
  2 {
  3     HttpContext context;
  4     try
  5     {
  6         context = new HttpContext(wr, false);//1. 创建HttpContext实例
  7     }
  8     catch
  9     {
 10         wr.SendStatus(400"Bad Request");
 11         wr.SendKnownResponseHeader(12"text/html; charset=utf-8");
 12         byte[] bytes = Encoding.ASCII.GetBytes("<html><body>Bad Request</body></html>");
 13         wr.SendResponseFromMemory(bytes, bytes.Length);
 14         wr.FlushResponse(true);
 15         wr.EndOfRequest();
 16         return;
 17     }
 18     wr.SetEndOfSendNotification(this._asyncEndOfSendCallback, context);
 19     Interlocked.Increment(ref this._activeRequestCount);
 20     HostingEnvironment.IncrementBusyCount();
 21     try
 22     {
 23         try
 24         {
 25             this.EnsureFirstRequestInit(context);//2.在EnsureFirstRequestInit中通过调用System.Web.HttpRuntime.FirstRequestInit进行一些初始化工作,比如:将Web.Config配置读到到RuntimeConfig中,从bin目录中装载所有dll文件。
 26 
 27         }
 28         catch
 29         {
 30             if (!context.Request.IsDebuggingRequest)
 31             {
 32                 throw;
 33             }
 34         }
 35         context.Response.InitResponseWriter();
 36         IHttpHandler applicationInstance = HttpApplicationFactory.GetApplicationInstance(context);
 37 //3.通过调用HttpApplicationFactory.GetApplicationInstance创建HttpApplication实例。
 38         if (applicationInstance == null)
 39         {
 40             throw new HttpException(SR.GetString("Unable_create_app_object"));
 41         }
 42         if (EtwTrace.IsTraceEnabled(51))
 43         {
 44             EtwTrace.Trace(EtwTraceType.ETW_TYPE_START_HANDLER, context.WorkerRequest, applicationInstance.GetType().FullName, "Start");
 45         }
 46         if (applicationInstance is IHttpAsyncHandler)
 47         {
 48             IHttpAsyncHandler handler2 = (IHttpAsyncHandler) applicationInstance;
 49             context.AsyncAppHandler = handler2;
 50             handler2.BeginProcessRequest(context, this._handlerCompletionCallback, context);//4.调用HttpApplication实例的BeginProcessRequest异步处理请求。
 51      上面所讲的_execSteps中所发生的许多事情,都是在HttpRuntime调用HttpApplication BeginProcessRequest之后,在BeginProcessRequest中调用ResumeSteps后执行的
 52         }
 53         else
 54         {
 55             applicationInstance.ProcessRequest(context);
 56             this.FinishRequest(context.WorkerRequest, context, null);
 57         }
 58     }
 59     catch (Exception exception)
 60     {
 61         context.Response.InitResponseWriter();
 62         this.FinishRequest(wr, context, exception);
 63     }
 64 }
 65 
 66 
 67 internal static IHttpHandler GetApplicationInstance(HttpContext context)
 68 {
 69     if (_customApplication != null)
 70     {
 71         return _customApplication;
 72     }
 73     if (context.Request.IsDebuggingRequest)
 74     {
 75         return new HttpDebugHandler();
 76     }
 77     _theApplicationFactory.EnsureInited();
 78     _theApplicationFactory.EnsureAppStartCalled(context);
 79     return _theApplicationFactory.GetNormalApplicationInstance(context);
 80 }
 81 
 82 1) HttpApplicationFactory._theApplicationFactory.EnsureInited();
 83      该方法检查HttpApplicationFactory是否被初始化,如果没有,就通过HttpApplicationFactory.Init()进行初始化。
 84 在Init()中,先获取global.asax文件的完整路径,然后调用CompileApplication()对global.asax进行编译。
 85 那编译是如何进行的呢?
 86      编译的工作由BuildManager完成的。BuildManager先得到GlobalAsaxType(也就是HttpApplication),然后调用BuildManager.GetGlobalAsaxBuildResult()=》GetGlobalAsaxBuildResultInternal()=》EnsureTopLevelFilesCompiled()进行编译。
 87      在EnsureTopLevelFilesCompiled中,先进行CompilationStage.TopLevelFiles编译,对下面三个目录中的文件进行编译:
 88 a. CompileResourcesDirectory();
 89 编译App_GlobalResources目录。
 90 b. CompileWebRefDirectory();
 91 编译App_WebReferences目录。
 92 c. CompileCodeDirectories();
 93 编译App_Code目录。
 94 
 95      接着进行CompilationStage.GlobalAsax 编译,对global.asax进行编译,方法调用情况:CompileGlobalAsax()=》ApplicationBuildProvider.GetGlobalAsaxBuildResult(BuildManager.IsPrecompiledApp)。
 96      在GetGlobalAsaxBuildResult中具体的编译是由ApplicationBuildProvider与BuildProvidersCompiler共同完成的。
 97      BuildProvidersCompiler.PerformBuild();进行编译工作。
 98      ApplicationBuildProvider.GetBuildResult得到编译的结果。
 99      编译成功后,会在C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\相应的目录中生成类似App_global.asax.mlgx7n2v.dll的dll文件。
100      编译生成的类名为ASP.global_asax,继承自HttpApplication。
101 注:如果Web目录中没有Global.asax文件,就不会编译生成App_global.asax.mlgx7n2v.dll这样的文件。
102 
103 2) HttpApplicationFactory._theApplicationFactory.EnsureAppStartCalled(context);
104      创建特定的HttpApplication实例,触发ApplicationOnStart事件,执行ASP.global_asax中的Application_Start(object sender, EventArgs e)方法。这里创建的HttpApplication实例在处理完事件后,就被回收。
105 
106 3) HttpApplicationFactory._theApplicationFactory.GetNormalApplicationInstance(context);
107      该 方法创建HttpApplication实例并进行初始化(调用System.Web.HttpApplication. InitInternal()方法)。
108 创建HttpApplication实例是根据实际的_theApplicationType进行创建。如果Web目录中没有global.asa文件,也就是说没有动态编译生成ASP.global_asax类型,那就直接实例化HttpApplication。如果创建了ASP.global_asax类型,那就对ASP.global_asa进行实例化。
109 
110 
111 
112  
113 private HttpApplication GetNormalApplicationInstance(HttpContext context)
114 {
115     HttpApplication application = null;
116     lock (this._freeList)
117     {
118         if (this._numFreeAppInstances > 0)
119         {
120             application = (HttpApplication) this._freeList.Pop();
121             this._numFreeAppInstances--;
122             if (this._numFreeAppInstances < this._minFreeAppInstances)
123             {
124                 this._minFreeAppInstances = this._numFreeAppInstances;
125             }
126         }
127     }
128     if (application == null)
129     {
130         application = (HttpApplication) HttpRuntime.CreateNonPublicInstance(this._theApplicationType);
131         using (new ApplicationImpersonationContext())
132         {
133             application.InitInternal(context, this._state, this._eventHandlerMethods);//(调用System.Web.HttpApplication. InitInternal()方法)。
134 
135         }
136     }
137     return application;
138 }
139 
140 
141 internal void InitInternal(HttpContext context, HttpApplicationState state, MethodInfo[] handlers)
142 {
143     this._state = state;
144     PerfCounters.IncrementCounter(AppPerfCounter.PIPELINES);
145     try
146     {
147         try
148         {
149             this._initContext = context;
150             this._initContext.ApplicationInstance = this;
151             context.ConfigurationPath = context.Request.ApplicationPathObject;
152             using (new HttpContextWrapper(context))
153             {
154                 if (HttpRuntime.UseIntegratedPipeline)
155                 {
156                     try
157                     {
158                         context.HideRequestResponse = true;
159                         this._hideRequestResponse = true;
160                         this.InitIntegratedModules();
161                         goto Label_006B;
162                     }
163                     finally
164                     {
165                         context.HideRequestResponse = false;
166                         this._hideRequestResponse = false;
167                     }
168                 }
169                 this.InitModules();
170 //1. InitModules():根据Web.Config的设置,创建相应的HttpModules。
171 
172             Label_006B:
173                 if (handlers != null)
174                 {
175                     this.HookupEventHandlersForApplicationAndModules(handlers);
176 //根据发生的事件,调用HttpApplication实例中相应的事件处理函数。
177 
178                 }
179                 this._context = context;
180                 if (HttpRuntime.UseIntegratedPipeline && (this._context != null))
181                 {
182                     this._context.HideRequestResponse = true;
183                 }
184                 this._hideRequestResponse = true;
185                 try
186                 {
187                     this.Init();
188                 }
189                 catch (Exception exception)
190                 {
191                     this.RecordError(exception);
192                 }
193             }
194             if (HttpRuntime.UseIntegratedPipeline && (this._context != null))
195             {
196                 this._context.HideRequestResponse = false;
197             }
198             this._hideRequestResponse = false;
199             this._context = null;
200             this._resumeStepsWaitCallback = new WaitCallback(this.ResumeStepsWaitCallback);
201             if (HttpRuntime.UseIntegratedPipeline)
202             {
203                 this._stepManager = new PipelineStepManager(this);
204             }
205             else
206             {
207                 this._stepManager = new ApplicationStepManager(this);
208             }
209             this._stepManager.BuildSteps(this._resumeStepsWaitCallback);
210         }
211         finally
212         {
213             this._initInternalCompleted = true;
214             context.ConfigurationPath = null;
215             this._initContext.ApplicationInstance = null;
216             this._initContext = null;
217         }
218     }
219     catch
220     {
221         throw;
222     }
223 }
224 
225 
226 internal override void BuildSteps(WaitCallback stepCallback)
227 {
228     ArrayList steps = new ArrayList();
229     HttpApplication app = base._application;
230     bool flag = false;
231     UrlMappingsSection urlMappings = RuntimeConfig.GetConfig().UrlMappings;
232     flag = urlMappings.IsEnabled && (urlMappings.UrlMappings.Count > 0);
233     steps.Add(new HttpApplication.ValidatePathExecutionStep(app));
234     if (flag)
235     {
236         steps.Add(new HttpApplication.UrlMappingsExecutionStep(app));
237     }
238     app.CreateEventExecutionSteps(HttpApplication.EventBeginRequest, steps);
239     app.CreateEventExecutionSteps(HttpApplication.EventAuthenticateRequest, steps);
240     app.CreateEventExecutionSteps(HttpApplication.EventDefaultAuthentication, steps);
241     app.CreateEventExecutionSteps(HttpApplication.EventPostAuthenticateRequest, steps);
242     app.CreateEventExecutionSteps(HttpApplication.EventAuthorizeRequest, steps);
243     app.CreateEventExecutionSteps(HttpApplication.EventPostAuthorizeRequest, steps);
244     app.CreateEventExecutionSteps(HttpApplication.EventResolveRequestCache, steps);
245     app.CreateEventExecutionSteps(HttpApplication.EventPostResolveRequestCache, steps);
246     steps.Add(new HttpApplication.MapHandlerExecutionStep(app));
247     app.CreateEventExecutionSteps(HttpApplication.EventPostMapRequestHandler, steps);
248     app.CreateEventExecutionSteps(HttpApplication.EventAcquireRequestState, steps);
249     app.CreateEventExecutionSteps(HttpApplication.EventPostAcquireRequestState, steps);
250     app.CreateEventExecutionSteps(HttpApplication.EventPreRequestHandlerExecute, steps);
251     steps.Add(new HttpApplication.CallHandlerExecutionStep(app));
252     app.CreateEventExecutionSteps(HttpApplication.EventPostRequestHandlerExecute, steps);
253     app.CreateEventExecutionSteps(HttpApplication.EventReleaseRequestState, steps);
254     app.CreateEventExecutionSteps(HttpApplication.EventPostReleaseRequestState, steps);
255     steps.Add(new HttpApplication.CallFilterExecutionStep(app));
256     app.CreateEventExecutionSteps(HttpApplication.EventUpdateRequestCache, steps);
257     app.CreateEventExecutionSteps(HttpApplication.EventPostUpdateRequestCache, steps);
258     this._endRequestStepIndex = steps.Count;
259     app.CreateEventExecutionSteps(HttpApplication.EventEndRequest, steps);
260     steps.Add(new HttpApplication.NoopExecutionStep());
261     this._execSteps = new HttpApplication.IExecutionStep[steps.Count];
262     steps.CopyTo(this._execSteps);
263     this._resumeStepsWaitCallback = stepCallback;
264 }
265 
266  
267 
268  
269 
270 
271  
272 
273  
274 
275 
posted @ 2009-11-13 22:21  awp110  阅读(263)  评论(0编辑  收藏  举报