你必須知道ASP.NET知識------從IIS到httpmodule(第一篇)


一、寫在前面

  最近有時間,順便將這系列洗完,接着上文:IIS各個版本知識總結

  這篇文章原本計划寫到HttpHandler為止,但限於篇幅就寫到httpmodule

  本文有不足之處,求指正,希望我能將它分析透徹.

二、回顧--我們還是從IIS說起

  從上文(IIS各個版本知識總結)可以很清楚地意思到經典模式和集成模式的區別:集成模式是一個偉大的改進,讓IIS集成了.NET功能(不在依靠之前IIS版本的aspnet_ISPAI.DLL).

  所以,對於我們所開發的ASP.NET程序而言,這些完全不必知道;但運行環境自己必須知道發生了什么情況.

  所以兩者的主要區別在於:從w3wp.exe初始化httpapplication這一階段.

 

三、看看經典模式(包括IIS6)的過程

IIS的處理進程到w3wp這一階段后,iis會通過com的方式創建AppManagerAppDomainFactory對象,AppManagerAppDomainFactory會

在Create方法中創建ISAPIRuntime對象.代碼如下.

using System;
using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;
using System.Runtime.Remoting;
using System.Security.Permissions;
using System.Web.Util;
namespace System.Web.Hosting
{
    [SecurityPermission(SecurityAction.LinkDemand, Unrestricted = true)]
    public sealed class AppManagerAppDomainFactory : IAppManagerAppDomainFactory
    {
        private ApplicationManager _appManager;
        public AppManagerAppDomainFactory()
        {
            this._appManager = ApplicationManager.GetApplicationManager();
            this._appManager.Open();
        }
        [return: MarshalAs(UnmanagedType.Interface)]
        public object Create(string appId, string appPath)
        {
            object result;
            try
            {
                if (appPath[0] == '.')
                {
                    FileInfo fileInfo = new FileInfo(appPath);
                    appPath = fileInfo.FullName;
                }
                if (!StringUtil.StringEndsWith(appPath, '\\'))
                {
                    appPath += "\\";
                }
                ISAPIApplicationHost appHost = new ISAPIApplicationHost(appId, appPath, false);
                ISAPIRuntime iSAPIRuntime = (ISAPIRuntime)this._appManager.CreateObjectInternal(appId, typeof(ISAPIRuntime), appHost, false, null);
                iSAPIRuntime.StartProcessing();
                result = new ObjectHandle(iSAPIRuntime);
            }
            catch (Exception)
            {
                throw;
            }
            return result;
        }
        public void Stop()
        {
            this._appManager.Close();
        }
        internal static string ConstructSimpleAppName(string virtPath)
        {
            if (virtPath.Length <= 1)
            {
                return "root";
            }
            return virtPath.Substring(1).ToLower(CultureInfo.InvariantCulture).Replace('/', '_');
        }
    }
}
View Code

最終將流程交由ProcessRequest處理,代碼如下.接着如紅色處,由HttpRuntime.ProcessRequestNoDemand(iSAPIWorkerRequest)處理

public int ProcessRequest(IntPtr ecb, int iWRType)
        {
            IntPtr intPtr = IntPtr.Zero;
            if (iWRType == 2)
            {
                intPtr = ecb;
                ecb = UnsafeNativeMethods.GetEcb(intPtr);
            }
            ISAPIWorkerRequest iSAPIWorkerRequest = null;
            int result;
            try
            {
                bool useOOP = iWRType == 1;
         //注:internal abstract class ISAPIWorkerRequest : HttpWorkerRequest iSAPIWorkerRequest
= ISAPIWorkerRequest.CreateWorkerRequest(ecb, useOOP); iSAPIWorkerRequest.Initialize(); string appPathTranslated = iSAPIWorkerRequest.GetAppPathTranslated(); string appDomainAppPathInternal = HttpRuntime.AppDomainAppPathInternal; if (appDomainAppPathInternal == null || StringUtil.EqualsIgnoreCase(appPathTranslated, appDomainAppPathInternal)) { HttpRuntime.ProcessRequestNoDemand(iSAPIWorkerRequest); result = 0; } else { HttpRuntime.ShutdownAppDomain(ApplicationShutdownReason.PhysicalApplicationPathChanged, SR.GetString("Hosting_Phys_Path_Changed", new object[] { appDomainAppPathInternal, appPathTranslated })); result = 1; } } catch (Exception ex) { //.................................. } return result; }

ISAPIWorkerRequest是對請求信息的一層C++封裝.

四、HttpRuntime中發生的事情

接着上面 HttpRuntime.ProcessRequestNoDemand(iSAPIWorkerRequest);

internal static void ProcessRequestNoDemand(HttpWorkerRequest wr)
        {
            RequestQueue requestQueue = HttpRuntime._theRuntime._requestQueue;
            wr.UpdateInitialCounters();
            if (requestQueue != null)
            {
                wr = requestQueue.GetRequestToExecute(wr);
            }
            if (wr != null)
            {
                HttpRuntime.CalculateWaitTimeAndUpdatePerfCounter(wr);
                wr.ResetStartTime();
                HttpRuntime.ProcessRequestNow(wr);
            }
        }
        internal static void ProcessRequestNow(HttpWorkerRequest wr)
        {
            HttpRuntime._theRuntime.ProcessRequestInternal(wr);
        }
View Code

我們看到方法進入

private void ProcessRequestInternal(HttpWorkerRequest wr)

其結構如下

private void ProcessRequestInternal(HttpWorkerRequest wr)
        {
            Interlocked.Increment(ref this._activeRequestCount);
            if (this._disposingHttpRuntime)
            {
                try
                {
                    wr.SendStatus(503, "Server Too Busy");
                    wr.SendKnownResponseHeader(12, "text/html; charset=utf-8");
                    byte[] bytes = Encoding.ASCII.GetBytes("<html><body>Server Too Busy</body></html>");
                    wr.SendResponseFromMemory(bytes, bytes.Length);
                    wr.FlushResponse(true);
                    wr.EndOfRequest();
                }
                finally
                {
                    Interlocked.Decrement(ref this._activeRequestCount);
                }
                return;
            }
            HttpContext httpContext;
            try
            {
                httpContext = new HttpContext(wr, false);
            }
            catch
            {
                try
                {
                    wr.SendStatus(400, "Bad Request");
                    wr.SendKnownResponseHeader(12, "text/html; charset=utf-8");
                    byte[] bytes2 = Encoding.ASCII.GetBytes("<html><body>Bad Request</body></html>");
                    wr.SendResponseFromMemory(bytes2, bytes2.Length);
                    wr.FlushResponse(true);
                    wr.EndOfRequest();
                    return;
                }
                finally
                {
                    Interlocked.Decrement(ref this._activeRequestCount);
                }
            }
            wr.SetEndOfSendNotification(this._asyncEndOfSendCallback, httpContext);
            HostingEnvironment.IncrementBusyCount();
            try
            {
                try
                {
                    this.EnsureFirstRequestInit(httpContext);
                }
                catch
                {
                    if (!httpContext.Request.IsDebuggingRequest)
                    {
                        throw;
                    }
                }
                httpContext.Response.InitResponseWriter();
                IHttpHandler applicationInstance = HttpApplicationFactory.GetApplicationInstance(httpContext);
                if (applicationInstance == null)
                {
                    throw new HttpException(SR.GetString("Unable_create_app_object"));
                }
                if (EtwTrace.IsTraceEnabled(5, 1))
                {
                    EtwTrace.Trace(EtwTraceType.ETW_TYPE_START_HANDLER, httpContext.WorkerRequest, applicationInstance.GetType().FullName, "Start");
                }
                if (applicationInstance is IHttpAsyncHandler)
                {
                    IHttpAsyncHandler httpAsyncHandler = (IHttpAsyncHandler)applicationInstance;
                    httpContext.AsyncAppHandler = httpAsyncHandler;
                    httpAsyncHandler.BeginProcessRequest(httpContext, this._handlerCompletionCallback, httpContext);
                }
                else
                {
                    applicationInstance.ProcessRequest(httpContext);
                    this.FinishRequest(httpContext.WorkerRequest, httpContext, null);
                }
            }
            catch (Exception e)
            {
                httpContext.Response.InitResponseWriter();
                this.FinishRequest(wr, httpContext, e);
            }
        }
View Code

傳說中的HttpApplication就是在這里初始化的.

IHttpHandler applicationInstance = HttpApplicationFactory.GetApplicationInstance(httpContext);//因為HttpApplication實現了IHttpHandler接口

最終通過BuildManager.GetGlobalAsaxType()獲取對應的Global.asax所告知的類型進行HttpApplication的實例化.

 

internal static IHttpHandler GetApplicationInstance(HttpContext context)
        {
            if (HttpApplicationFactory._customApplication != null)
            {
                return HttpApplicationFactory._customApplication;
            }
            if (context.Request.IsDebuggingRequest)
            {
                return new HttpDebugHandler();
            }
            HttpApplicationFactory._theApplicationFactory.EnsureInited();
            HttpApplicationFactory._theApplicationFactory.EnsureAppStartCalled(context);
            return HttpApplicationFactory._theApplicationFactory.GetNormalApplicationInstance(context);
        }

 

private HttpApplication GetNormalApplicationInstance(HttpContext context)
        {
            HttpApplication httpApplication = null;
            lock (this._freeList)
            {
                if (this._numFreeAppInstances > 0)
                {
                    httpApplication = (HttpApplication)this._freeList.Pop();
                    this._numFreeAppInstances--;
                    if (this._numFreeAppInstances < this._minFreeAppInstances)
                    {
                        this._minFreeAppInstances = this._numFreeAppInstances;
                    }
                }
            }
            if (httpApplication == null)
            {
                httpApplication = (HttpApplication)HttpRuntime.CreateNonPublicInstance(this._theApplicationType);
                using (new ApplicationImpersonationContext())
                {
                    httpApplication.InitInternal(context, this._state, this._eventHandlerMethods);//注意:這里是主戰場
                }
            }
            if (AppSettings.UseTaskFriendlySynchronizationContext)
            {
                httpApplication.ApplicationInstanceConsumersCounter = new CountdownTask(1);
                httpApplication.ApplicationInstanceConsumersCounter.Task.ContinueWith(delegate(Task _, object o)
                {
                    HttpApplicationFactory.RecycleApplicationInstance((HttpApplication)o);
                }, httpApplication, TaskContinuationOptions.ExecuteSynchronously);
            }
            return httpApplication;
        }

五、主戰場中的發生的事情

internal void InitInternal(HttpContext context, HttpApplicationState state, MethodInfo[] handlers)
        {
            this._state = state;
            PerfCounters.IncrementCounter(AppPerfCounter.PIPELINES);
            try
            {
                try
                {
                    this._initContext = context;
                    this._initContext.ApplicationInstance = this;
                    context.ConfigurationPath = context.Request.ApplicationPathObject;
                    using (new DisposableHttpContextWrapper(context))
                    {
                        if (HttpRuntime.UseIntegratedPipeline)
                        {
                            try
                            {
                                context.HideRequestResponse = true;
                                this._hideRequestResponse = true;
                                this.InitIntegratedModules();
                                goto IL_6B;
                            }
                            finally
                            {
                                context.HideRequestResponse = false;
                                this._hideRequestResponse = false;
                            }
                        }
                        this.InitModules();
                        IL_6B:
                        if (handlers != null)
                        {
                            this.HookupEventHandlersForApplicationAndModules(handlers);
                        }
                        this._context = context;
                        if (HttpRuntime.UseIntegratedPipeline && this._context != null)
                        {
                            this._context.HideRequestResponse = true;
                        }
                        this._hideRequestResponse = true;
                        try
                        {
                            this.Init();
                        }
                        catch (Exception error)
                        {
                            this.RecordError(error);
                        }
                    }
                    if (HttpRuntime.UseIntegratedPipeline && this._context != null)
                    {
                        this._context.HideRequestResponse = false;
                    }
                    this._hideRequestResponse = false;
                    this._context = null;
                    this._resumeStepsWaitCallback = new WaitCallback(this.ResumeStepsWaitCallback);
                    if (HttpRuntime.UseIntegratedPipeline)
                    {
                        this._stepManager = new HttpApplication.PipelineStepManager(this);
                    }
                    else
                    {
                        this._stepManager = new HttpApplication.ApplicationStepManager(this);
                    }
                    this._stepManager.BuildSteps(this._resumeStepsWaitCallback);
                }
                finally
                {
                    this._initInternalCompleted = true;
                    context.ConfigurationPath = null;
                    this._initContext.ApplicationInstance = null;
                    this._initContext = null;
                }
            }
            catch
            {
                throw;
            }
        }

 待續................................

六、求關注、求推薦

        兄台給點鼓勵吧 O(∩_∩)O~,你的鼓勵是我繼續寫好這一系列的理由


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM