ASP.NET 运行机制

时间:2024-01-02 23:25:44

原本今天打算继续写ASP.NET MVC第四天的。但是由于里面涉及到asp.net运行机制的原理,如果不分析一下这里,mvc想说清楚还是挺困难的。既然要提到asp.net运行机制,所以打算还是说详细一点的好。记录mvc第一天的时候就说过,asp.net mvc也是基于asp.net运行机制的(也就是原理)。网上也有很多讲解asp.net运行机制的,我在这里说一下自己的认识,我们开始吧。

我们从web程序的入口开始。那就要先说到iis了,大家都知道,这是web服务软件。将web程序部署到iis过的人都知道,如果不做任何处理,我们写的webform是不能运行的。为什么非要执行aspnet_regiis才可以呢?我们看一下电脑路径C:\Windows\Microsoft.NET\Framework\v4.0.30319,aspnet_regiis.exe就在这里路径下。我们简单说一下原因,看下iis的历史,在百度上没有查到iis软件发布的年限,但至少iis在windows 2000的时候就存在了,而我们的.net framework在2002-02-13的时候才发布1.0版本,是啊,我们都知道微软很厉害,但就是在厉害他也不会强大到可以预测几年后的软件运行机制吧。也就是说iis对.net framework还说就是个“古董”,他不可能会知道.net framewrok运行机制,更不可能知道asp.net的运行机制。早起的iis也只能处理静态页面,也就类似于html,js,图片之类的东西。但现在如果我们想将asp.net 程序部署到iis上怎么办呢?对,扩展,使用扩展程序,我们运行aspnet_regiis.exe也就是将扩展程序(aspnet_isapi)注入到iis中,这样iis就可以处理了?---------哈哈,iis还是处理处理不了asp.net程序,但是后注入的程序可以告诉iis,我扩展程序可以处理什么样的程序,你如果处理不了,可以尝试交给我处理。

看一下上面说到的路经下面有个aspnet_isapi.dll,我们只是简单的说一下这里,这个dll是使用c/c++写的,并不是c#写的,所以我们无法反编译成c#代码。这是个承上启下的动态库,因为c/c++并不是我们考虑的范围内,我们直接认为这个程序将请求交给我们“在乎”的程序,下面我们开始反编译我们“在乎”程序。反编译工具中查找ISAPIRuntime这个类,下面是我反编译出来的结果这个类是system.web程序集下的类

 public sealed class ISAPIRuntime : MarshalByRefObject, IISAPIRuntime, IISAPIRuntime2, IRegisteredObject
{
// Fields
private static int _isThisAppDomainRemovedFromUnmanagedTable;
private const int WORKER_REQUEST_TYPE_IN_PROC = ;
private const int WORKER_REQUEST_TYPE_IN_PROC_VERSION_2 = ;
private const int WORKER_REQUEST_TYPE_OOP = ; // Methods
[SecurityPermission(SecurityAction.Demand, Unrestricted=true)]
public ISAPIRuntime();
[SecurityPermission(SecurityAction.LinkDemand, Unrestricted=true)]
public void DoGCCollect();
public override object InitializeLifetimeService();
[SecurityPermission(SecurityAction.LinkDemand, Unrestricted=true)]
public int ProcessRequest(IntPtr ecb, int iWRType);
internal static void RemoveThisAppDomainFromUnmanagedTable();
[SecurityPermission(SecurityAction.LinkDemand, Unrestricted=true)]
public void StartProcessing();
[SecurityPermission(SecurityAction.LinkDemand, Unrestricted=true)]
public void StopProcessing();
[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
void IISAPIRuntime2.DoGCCollect();
[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
int IISAPIRuntime2.ProcessRequest(IntPtr ecb, int iWRType);
[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
void IISAPIRuntime2.StartProcessing();
[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
void IISAPIRuntime2.StopProcessing();
void IRegisteredObject.Stop(bool immediate);
} Expand Methods

其实我贴出代码没有别的意思,就是想用事实说话,过多的内容我们不看,我们只看里面的public int ProcessRequest(IntPtr ecb, int iWRType)处理请求方法。我们先看一下参数类型吧,IntPtr?有调c/c++动态库的人会知道这是c/c++里面指针类型,我们不用过多的考虑。我自己分析的,不知道对不对,正因为这是IntPtr,所以该类应该是调用了c/c++相关的动态库了,不然这里也没有必要用到。这样流程就出来了,IIS——》aspnet_isapi(c/c++相关动态库)——》ISAPIRuntime类;需要提到一点的是,IntPtr是个指针,指针会指向一块内存区域,可能很大,也可能很小。我认为请求的内容放在了这块区域中,从这里面可以获取到浏览器请求头的内容下面是ProcessRequest方法的内容

 [SecurityPermission(SecurityAction.LinkDemand, Unrestricted=true)]
public int ProcessRequest(IntPtr ecb, int iWRType)
{
IntPtr zero = IntPtr.Zero;
if (iWRType == )
{
zero = ecb;
ecb = UnsafeNativeMethods.GetEcb(zero);
}
ISAPIWorkerRequest wr = null;
try
{
bool useOOP = iWRType == ;
wr = ISAPIWorkerRequest.CreateWorkerRequest(ecb, useOOP);
wr.Initialize();
string appPathTranslated = wr.GetAppPathTranslated();
string appDomainAppPathInternal = HttpRuntime.AppDomainAppPathInternal;
if ((appDomainAppPathInternal == null) || StringUtil.EqualsIgnoreCase(appPathTranslated, appDomainAppPathInternal))
{
HttpRuntime.ProcessRequestNoDemand(wr);
return ;
}
HttpRuntime.ShutdownAppDomain(ApplicationShutdownReason.PhysicalApplicationPathChanged, SR.GetString("Hosting_Phys_Path_Changed", new object[] { appDomainAppPathInternal, appPathTranslated }));
return ;
}
catch (Exception exception)
{
try
{
WebBaseEvent.RaiseRuntimeError(exception, this);
}
catch
{
}
if ((wr == null) || !(wr.Ecb == IntPtr.Zero))
{
throw;
}
if (zero != IntPtr.Zero)
{
UnsafeNativeMethods.SetDoneWithSessionCalled(zero);
}
if (exception is ThreadAbortException)
{
Thread.ResetAbort();
}
return ;
}
}

下面我们来分析一下这里面的代码,我们只分析重要的部分。

这里新建了一个 ISAPIWorkerRequest wr = null;类,进行创建封装该对象,wr = ISAPIWorkerRequest.CreateWorkerRequest(ecb, useOOP);上面说了ecb是个指针,里面可以存储很多请求内容的。紧接着对wr进行初始化wr.Initialize();我们着重看HttpRuntime.ProcessRequestNoDemand(wr);注意这里使用的是HttpRuntime,一会我们还会分析该类,现在我们进入ProcessRequestNoDemand方法里面看看。这里面应该是关于多线程模型了

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

这时ISAPIRuntime已经将请求交给HttpRuntime类了,HttpRuntime类调用RequestQueue queue = _theRuntime._requestQueue;该类试图获取请求处理队列,我们可以简单的认为服务器在求情一个线程来处理该次浏览器的请求。wr = queue.GetRequestToExecute(wr);我们进入到GetRequestToExecute方法,

 internal HttpWorkerRequest GetRequestToExecute(HttpWorkerRequest wr)
{
int num;
int num2;
int num3;
ThreadPool.GetAvailableThreads(out num, out num2);
if (this._iis6)
{
num3 = num;
}
else
{
num3 = (num2 > num) ? num : num2;
}
if ((num3 < this._minExternFreeThreads) || (this._count != ))
{
bool isLocal = IsLocal(wr);
if ((isLocal && (num3 >= this._minLocalFreeThreads)) && (this._count == ))
{
return wr;
}
if (this._count >= this._queueLimit)
{
HttpRuntime.RejectRequestNow(wr, false);
return null;
}
this.QueueRequest(wr, isLocal);
if (num3 >= this._minExternFreeThreads)
{
wr = this.DequeueRequest(false);
return wr;
}
if (num3 >= this._minLocalFreeThreads)
{
wr = this.DequeueRequest(true);
return wr;
}
wr = null;
this.ScheduleMoreWorkIfNeeded();
}
return wr;
}

当然服务器不可能只有一个求情,如果同时有多个用户请求,这时队列中就可能没有线程可响应此次请求,在这里面就会调用this.ScheduleMoreWorkIfNeeded();从线程池中拿出一个来处理请求。下面我们返回ProcessRequestNoDemand()方法,该方法调用了ProcessRequestNow(wr);处理请求。

 internal static void ProcessRequestNow(HttpWorkerRequest wr)
{
_theRuntime.ProcessRequestInternal(wr);
}

我们只看ProcessRequestNow()方法

这个方法又调用了HttpRuntime的ProcessRequestInternal方法,接下来我们开始分析HttpRuntme类,

 public sealed class HttpRuntime
{
// Fields
private int _activeRequestCount;
private bool _apartmentThreading;
private string _appDomainAppId;
private string _appDomainAppPath;
private VirtualPath _appDomainAppVPath;
private string _appDomainId;
private Timer _appDomainShutdownTimer;
private WaitCallback _appDomainUnloadallback;
private byte[] _appOfflineMessage;
private HttpWorkerRequest.EndOfSendNotification _asyncEndOfSendCallback;
private bool _beforeFirstRequest;
private CacheInternal _cacheInternal;
private Cache _cachePublic;
private string _clientScriptPhysicalPath;
private string _clientScriptVirtualPath;
private string _codegenDir;
private bool _configInited;
private bool _debuggingEnabled;
private static string _DefaultPhysicalPathOnMapPathFailure;
private bool _disableProcessRequestInApplicationTrust;
private volatile bool _disposingHttpRuntime;
private bool _enableHeaderChecking;
private static bool _enablePrefetchOptimization;
private FileChangesMonitor _fcm;
private bool _firstRequestCompleted;
private DateTime _firstRequestStartTime;
private bool _fusionInited;
private AsyncCallback _handlerCompletionCallback;
private bool _hostingInitFailed;
private string _hostSecurityPolicyResolverType;
private static Version _iisVersion;
private Exception _initializationError;
private bool _isLegacyCas;
private bool _isOnUNCShare;
private DateTime _lastShutdownAttemptTime;
private NamedPermissionSet _namedPermissionSet;
private PolicyLevel _policyLevel;
private bool _processRequestInApplicationTrust;
private Profiler _profiler;
private AsyncCallback _requestNotificationCompletionCallback;
private RequestQueue _requestQueue;
private bool _shutdownInProgress;
private string _shutDownMessage;
private ApplicationShutdownReason _shutdownReason;
private string _shutDownStack;
private bool _shutdownWebEventRaised;
private string _tempDir;
private static HttpRuntime _theRuntime;
private RequestTimeoutManager _timeoutManager;
private string _trustLevel;
private static bool _useIntegratedPipeline;
private bool _userForcedShutdown;
private string _wpUserId;
private static BuildManagerHostUnloadEventHandler AppDomainShutdown;
private const string AppOfflineFileName = "App_Offline.htm";
private const string AspNetClientFilesParentVirtualPath = "/aspnet_client/system_web/";
private const string AspNetClientFilesSubDirectory = "asp.netclientfiles";
internal const string BinDirectoryName = "bin";
internal const string BrowsersDirectoryName = "App_Browsers";
internal const string CodeDirectoryName = "App_Code";
internal const string codegenDirName = "Temporary ASP.NET Files";
internal const string DataDirectoryName = "App_Data";
private static string DirectorySeparatorString;
private static string DoubleDirectorySeparatorString;
internal const string GlobalThemesDirectoryName = "Themes";
internal const string LocalResourcesDirectoryName = "App_LocalResources";
private const long MaxAppOfflineFileLength = 0x100000L;
internal const string profileFileName = "profileoptimization.prof";
internal const string ResourcesDirectoryName = "App_GlobalResources";
internal static byte[] s_autogenKeys;
private static Hashtable s_factoryCache;
private static FactoryGenerator s_factoryGenerator;
private static object s_factoryLock;
private static bool s_initialized;
private static bool s_initializedFactory;
private static string s_installDirectory;
private static char[] s_InvalidPhysicalPathChars;
private static bool s_isEngineLoaded;
internal const string ThemesDirectoryName = "App_Themes";
internal const string WebRefDirectoryName = "App_WebReferences"; // Events
internal static event BuildManagerHostUnloadEventHandler AppDomainShutdown; // Methods
static HttpRuntime();
[SecurityPermission(SecurityAction.LinkDemand, Unrestricted=true)]
public HttpRuntime();
internal static void AddAppDomainTraceMessage(string message);
private void AppDomainShutdownTimerCallback(object state);
private static void CalculateWaitTimeAndUpdatePerfCounter(HttpWorkerRequest wr);
[FileIOPermission(SecurityAction.Assert, Unrestricted=true)]
private void CheckAccessToTempDirectory();
internal static void CheckApplicationEnabled();
internal static void CheckAspNetHostingPermission(AspNetHostingPermissionLevel level, string errorMessageId);
[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
internal static void CheckFilePermission(string path);
internal static void CheckFilePermission(string path, bool writePermissions);
internal static void CheckVirtualFilePermission(string virtualPath);
[SecurityPermission(SecurityAction.Demand, Unrestricted=true)]
public static void Close();
internal static void CoalesceNotifications();
private void CreateCache();
[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
internal static object CreateNonPublicInstance(Type type);
[PermissionSet(SecurityAction.Assert, Unrestricted=true)]
internal static object CreateNonPublicInstance(Type type, object[] args);
private static PolicyLevel CreatePolicyLevel(string configFile, string appDir, string binDir, string strOriginUrl, out bool foundGacToken);
internal static object CreatePublicInstance(Type type);
internal static object CreatePublicInstance(Type type, object[] args);
internal static void DecrementActivePipelineCount();
private void Dispose();
private void DisposeAppDomainShutdownTimer();
private void EndOfSendCallback(HttpWorkerRequest wr, object arg);
private void EnsureAccessToApplicationDirectory();
private void EnsureFirstRequestInit(HttpContext context);
internal static void FailIfNoAPTCABit(Type t, XmlNode node);
internal static void FailIfNoAPTCABit(Type t, ElementInformation elemInfo, string propertyName);
internal static object FastCreatePublicInstance(Type type);
internal static void FinishPipelineRequest(HttpContext context);
private void FinishRequest(HttpWorkerRequest wr, HttpContext context, Exception e);
private void FinishRequestNotification(IIS7WorkerRequest wr, HttpContext context, ref RequestNotificationStatus status);
private void FirstRequestInit(HttpContext context);
internal static void ForceStaticInit();
private static string GetAppDomainString(string key);
internal static CacheInternal GetCacheInternal(bool createIfDoesNotExist);
private static string GetCurrentUserName();
internal static string GetGacLocation();
private void GetInitConfigSections(out CacheSection cacheSection, out TrustSection trustSection, out SecurityPolicySection securityPolicySection, out CompilationSection compilationSection, out HostingEnvironmentSection hostingEnvironmentSection, out Exception initException);
[AspNetHostingPermission(SecurityAction.Demand, Level=AspNetHostingPermissionLevel.Unrestricted)]
public static NamedPermissionSet GetNamedPermissionSet();
internal static string GetRelaxedMapPathResult(string originalResult);
internal static string GetSafePath(string path);
internal static bool HasAppPathDiscoveryPermission();
private static bool HasAPTCABit(Assembly assembly);
internal static bool HasAspNetHostingPermission(AspNetHostingPermissionLevel level);
internal static bool HasDbPermission(DbProviderFactory factory);
[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
internal static bool HasFilePermission(string path);
internal static bool HasFilePermission(string path, bool writePermissions);
internal static bool HasPathDiscoveryPermission(string path);
internal static bool HasUnmanagedPermission();
internal static bool HasWebPermission(Uri uri);
private void HostingInit(HostingEnvironmentFlags hostingFlags, PolicyLevel policyLevel, Exception appDomainCreationException);
internal static void IncrementActivePipelineCount();
private void Init();
private void InitApartmentThreading();
private void InitDebuggingSupport();
private void InitFusion(HostingEnvironmentSection hostingEnvironmentSection);
private void InitHeaderEncoding();
private static void InitHttpConfiguration();
private void InitializeHealthMonitoring();
internal static void InitializeHostingFeatures(HostingEnvironmentFlags hostingFlags, PolicyLevel policyLevel, Exception appDomainCreationException);
private bool InitiateShutdownOnce();
private void InitRequestQueue();
private void InitTrace(HttpContext context);
internal static bool IsPathWithinAppRoot(string path);
internal static bool IsTypeAccessibleFromPartialTrust(Type t);
internal static bool IsTypeAllowedInConfig(Type t);
internal static string MakeFileUrl(string path);
internal static void OnAppDomainShutdown(BuildManagerHostUnloadEventArgs e);
private void OnAppOfflineFileChange(object sender, FileChangeEvent e);
internal static void OnConfigChange(string message);
private void OnCriticalDirectoryChange(object sender, FileChangeEvent e);
private void OnHandlerCompletion(IAsyncResult ar);
private void OnRequestNotificationCompletion(IAsyncResult ar);
private void OnRequestNotificationCompletionHelper(IAsyncResult ar);
private void OnSecurityPolicyFileChange(object sender, FileChangeEvent e);
internal static void PopulateIISVersionInformation();
[PermissionSet(SecurityAction.Assert, Unrestricted=true)]
private void PreloadAssembliesFromBin();
private void PreloadAssembliesFromBinRecursive(DirectoryInfo dirInfo);
[AspNetHostingPermission(SecurityAction.Demand, Level=AspNetHostingPermissionLevel.Medium)]
public static void ProcessRequest(HttpWorkerRequest wr);
private void ProcessRequestInternal(HttpWorkerRequest wr);
internal static void ProcessRequestNoDemand(HttpWorkerRequest wr);
internal static RequestNotificationStatus ProcessRequestNotification(IIS7WorkerRequest wr, HttpContext context);
private RequestNotificationStatus ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context);
internal static void ProcessRequestNow(HttpWorkerRequest wr);
private void RaiseShutdownWebEventOnce();
internal static void RecoverFromUnexceptedAppDomainUnload();
private void RejectRequestInternal(HttpWorkerRequest wr, bool silent);
internal static void RejectRequestNow(HttpWorkerRequest wr, bool silent);
private void RelaxMapPathIfRequired();
[PermissionSet(SecurityAction.Assert, Unrestricted=true)]
private void ReleaseResourcesAndUnloadAppDomain(object state);
internal static void ReportAppOfflineErrorMessage(HttpResponse response, byte[] appOfflineMessage);
internal static void RestrictIISFolders(HttpContext context);
private void SetAutoConfigLimits(ProcessModelSection pmConfig);
private static void SetAutogenKeys();
[SecurityPermission(SecurityAction.Assert, ControlThread=true)]
internal static void SetCurrentThreadCultureWithAssert(CultureInfo cultureInfo);
private static void SetExecutionTimePerformanceCounter(HttpContext context);
internal static void SetShutdownMessage(string message);
internal static void SetShutdownReason(ApplicationShutdownReason reason, string message);
private void SetThreadPoolLimits();
private void SetTrustLevel(TrustSection trustSection, SecurityPolicySection securityPolicySection);
private void SetTrustParameters(TrustSection trustSection, SecurityPolicySection securityPolicySection, PolicyLevel policyLevel);
private void SetUpCodegenDirectory(CompilationSection compilationSection);
private void SetUpDataDirectory();
internal static void SetUserForcedShutdown();
private static bool ShutdownAppDomain(string stackTrace);
[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
internal static bool ShutdownAppDomain(ApplicationShutdownReason reason, string message);
internal static bool ShutdownAppDomainWithStackTrace(ApplicationShutdownReason reason, string message, string stackTrace);
private void StartAppDomainShutdownTimer();
internal static void StartListeningToLocalResourcesDirectory(VirtualPath virtualDir);
private void StartMonitoringDirectoryRenamesAndBinDirectory();
private static void StaticInit();
public static void UnloadAppDomain();
private static void UpdatePerfCounters(int statusCode);
private void WaitForRequestsToFinish(int waitTimeoutMs); // Properties
internal static bool ApartmentThreading { get; }
public static string AppDomainAppId { get; }
public static string AppDomainAppPath { get; }
internal static string AppDomainAppPathInternal { get; }
public static string AppDomainAppVirtualPath { get; }
internal static VirtualPath AppDomainAppVirtualPathObject { get; }
internal static string AppDomainAppVirtualPathString { get; }
public static string AppDomainId { [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries"), AspNetHostingPermission(SecurityAction.Demand, Level=AspNetHostingPermissionLevel.High)] get; }
internal static string AppDomainIdInternal { get; }
internal static byte[] AppOfflineMessage { get; }
public static string AspClientScriptPhysicalPath { get; }
internal static string AspClientScriptPhysicalPathInternal { get; }
public static string AspClientScriptVirtualPath { get; }
public static string AspInstallDirectory { get; }
internal static string AspInstallDirectoryInternal { [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] get; }
public static string BinDirectory { get; }
internal static string BinDirectoryInternal { get; }
public static Cache Cache { get; }
internal static CacheInternal CacheInternal { [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] get; }
public static string ClrInstallDirectory { get; }
internal static string ClrInstallDirectoryInternal { get; }
internal static VirtualPath CodeDirectoryVirtualPath { get; }
public static string CodegenDir { get; }
internal static string CodegenDirInternal { get; }
internal static bool ConfigInited { get; }
internal static bool DebuggingEnabled { get; }
internal static bool DisableProcessRequestInApplicationTrust { get; }
internal static bool EnableHeaderChecking { get; }
internal static bool EnablePrefetchOptimization { [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] get; }
internal static FileChangesMonitor FileChangesMonitor { get; }
internal static bool FusionInited { get; }
internal static bool HostingInitFailed { get; }
internal static string HostSecurityPolicyResolverType { get; }
public static Version IISVersion { [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] get; }
internal static Exception InitializationException { get; set; }
internal static bool IsAspNetAppDomain { get; }
internal static bool IsEngineLoaded { [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] get; }
internal static bool IsFullTrust { get; }
internal static bool IsLegacyCas { get; }
internal static bool IsMapPathRelaxed { get; }
public static bool IsOnUNCShare { [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries"), AspNetHostingPermission(SecurityAction.Demand, Level=AspNetHostingPermissionLevel.Low)] get; }
internal static bool IsOnUNCShareInternal { get; }
internal static bool IsTrustLevelInitialized { get; }
private DateTime LastShutdownAttemptTime { get; set; }
public static string MachineConfigurationDirectory { get; }
internal static string MachineConfigurationDirectoryInternal { get; }
internal static NamedPermissionSet NamedPermissionSet { get; }
internal static PolicyLevel PolicyLevel { get; }
internal static bool ProcessRequestInApplicationTrust { get; }
internal static Profiler Profile { get; }
internal static RequestTimeoutManager RequestTimeoutManager { get; }
internal static VirtualPath ResourcesDirectoryVirtualPath { get; }
internal static bool ShutdownInProgress { get; }
internal static ApplicationShutdownReason ShutdownReason { get; }
public static Version TargetFramework { get; }
internal static string TempDirInternal { get; }
internal static string TrustLevel { get; }
internal static bool UseIntegratedPipeline { [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")] get; }
public static bool UsingIntegratedPipeline { [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] get; }
internal static VirtualPath WebRefDirectoryVirtualPath { get; }
internal static string WpUserId { get; }
} Expand Methods

看ProcessRequestInternal()方法

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

在这里创建了上下文 HttpContext context;对象,使用wr(wr中封装了请求信息)对象创建了上下文对象 context = new HttpContext(wr, false);

IHttpHandler applicationInstance = HttpApplicationFactory.GetApplicationInstance(context);使用HttpApplicationFactory创建HttpApplication对象,applicationInstance.ProcessRequest(context);在这个方法中会调用近20几个是事件,该对象在后面的事件中通过反射创建请求页面类的对象在第7个事件和第8个事件中间通过反射创建前台页面类对象,后续的事件之间又调用页面类对象的ProcessRequest方法,这就是我们写的asp.net程序后台类为什么有ProcessRequest方法了,我们应该知道前台页面类继承后台页面类,我在这里再贴一下HttpApplication类的代码
 [ToolboxItem(false)]
public class HttpApplication : IComponent, IDisposable, IHttpAsyncHandler, IHttpHandler, IRequestCompletedNotifier, ISyncContext
{
// Fields
private EventArgs _appEvent;
private bool _appLevelAutoCulture;
private bool _appLevelAutoUICulture;
private CultureInfo _appLevelCulture;
private CultureInfo _appLevelUICulture;
private RequestNotification _appPostNotifications;
private RequestNotification _appRequestNotifications;
private HttpAsyncResult _ar;
private AsyncAppEventHandlersTable _asyncEvents;
private HttpContext _context;
private string _currentModuleCollectionKey;
private static readonly DynamicModuleRegistry _dynamicModuleRegistry;
private byte[] _entityBuffer;
private EventHandlerList _events;
private Hashtable _handlerFactories;
private ArrayList _handlerRecycleList;
private bool _hideRequestResponse;
private HttpContext _initContext;
private bool _initInternalCompleted;
private static bool _initSpecialCompleted;
private Exception _lastError;
private HttpModuleCollection _moduleCollection;
private static List<ModuleConfigurationInfo> _moduleConfigInfo;
private PipelineModuleStepContainer[] _moduleContainers;
private static Hashtable _moduleIndexMap;
private Dictionary<string, RequestNotification> _pipelineEventMasks;
private WaitCallback _resumeStepsWaitCallback;
private CultureInfo _savedAppLevelCulture;
private CultureInfo _savedAppLevelUICulture;
private HttpSessionState _session;
private ISite _site;
private HttpApplicationState _state;
private StepManager _stepManager;
private bool _timeoutManagerInitialized;
internal CountdownTask ApplicationInstanceConsumersCounter;
internal static readonly string AutoCulture;
private static readonly object EventAcquireRequestState;
private static readonly object EventAuthenticateRequest;
private static readonly object EventAuthorizeRequest;
private static readonly object EventBeginRequest;
private static readonly object EventDefaultAuthentication;
private static readonly object EventDisposed;
private static readonly object EventEndRequest;
private static readonly object EventErrorRecorded;
private static readonly object EventLogRequest;
private static readonly object EventMapRequestHandler;
private static readonly object EventPostAcquireRequestState;
private static readonly object EventPostAuthenticateRequest;
private static readonly object EventPostAuthorizeRequest;
private static readonly object EventPostLogRequest;
private static readonly object EventPostMapRequestHandler;
private static readonly object EventPostReleaseRequestState;
private static readonly object EventPostRequestHandlerExecute;
private static readonly object EventPostResolveRequestCache;
private static readonly object EventPostUpdateRequestCache;
private static readonly object EventPreRequestHandlerExecute;
private static readonly object EventPreSendRequestContent;
private static readonly object EventPreSendRequestHeaders;
private static readonly object EventReleaseRequestState;
private static readonly object EventRequestCompleted;
private static readonly object EventResolveRequestCache;
private static readonly object EventUpdateRequestCache;
internal const string IMPLICIT_FILTER_MODULE = "AspNetFilterModule";
internal const string IMPLICIT_HANDLER = "ManagedPipelineHandler";
internal const string MANAGED_PRECONDITION = "managedHandler"; // Events
public event EventHandler AcquireRequestState;
public event EventHandler AuthenticateRequest;
public event EventHandler AuthorizeRequest;
public event EventHandler BeginRequest;
internal event EventHandler DefaultAuthentication;
public event EventHandler Disposed;
public event EventHandler EndRequest;
public event EventHandler Error;
public event EventHandler LogRequest;
public event EventHandler MapRequestHandler;
public event EventHandler PostAcquireRequestState;
public event EventHandler PostAuthenticateRequest;
public event EventHandler PostAuthorizeRequest;
public event EventHandler PostLogRequest;
public event EventHandler PostMapRequestHandler;
public event EventHandler PostReleaseRequestState;
public event EventHandler PostRequestHandlerExecute;
public event EventHandler PostResolveRequestCache;
public event EventHandler PostUpdateRequestCache;
public event EventHandler PreRequestHandlerExecute;
public event EventHandler PreSendRequestContent;
public event EventHandler PreSendRequestHeaders;
public event EventHandler ReleaseRequestState;
public event EventHandler RequestCompleted;
public event EventHandler ResolveRequestCache;
public event EventHandler UpdateRequestCache; // Methods
static HttpApplication();
public HttpApplication();
internal void AcquireNotifcationContextLock(ref bool locked);
private void AddEventMapping(string moduleName, RequestNotification requestNotification, bool isPostNotification, IExecutionStep step);
[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
public void AddOnAcquireRequestStateAsync(BeginEventHandler bh, EndEventHandler eh);
public void AddOnAcquireRequestStateAsync(BeginEventHandler beginHandler, EndEventHandler endHandler, object state);
[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
public void AddOnAuthenticateRequestAsync(BeginEventHandler bh, EndEventHandler eh);
public void AddOnAuthenticateRequestAsync(BeginEventHandler beginHandler, EndEventHandler endHandler, object state);
[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
public void AddOnAuthorizeRequestAsync(BeginEventHandler bh, EndEventHandler eh);
public void AddOnAuthorizeRequestAsync(BeginEventHandler beginHandler, EndEventHandler endHandler, object state);
[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
public void AddOnBeginRequestAsync(BeginEventHandler bh, EndEventHandler eh);
public void AddOnBeginRequestAsync(BeginEventHandler beginHandler, EndEventHandler endHandler, object state);
[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
public void AddOnEndRequestAsync(BeginEventHandler bh, EndEventHandler eh);
public void AddOnEndRequestAsync(BeginEventHandler beginHandler, EndEventHandler endHandler, object state);
public void AddOnLogRequestAsync(BeginEventHandler bh, EndEventHandler eh);
public void AddOnLogRequestAsync(BeginEventHandler beginHandler, EndEventHandler endHandler, object state);
public void AddOnMapRequestHandlerAsync(BeginEventHandler bh, EndEventHandler eh);
public void AddOnMapRequestHandlerAsync(BeginEventHandler beginHandler, EndEventHandler endHandler, object state);
[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
public void AddOnPostAcquireRequestStateAsync(BeginEventHandler bh, EndEventHandler eh);
public void AddOnPostAcquireRequestStateAsync(BeginEventHandler beginHandler, EndEventHandler endHandler, object state);
[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
public void AddOnPostAuthenticateRequestAsync(BeginEventHandler bh, EndEventHandler eh);
public void AddOnPostAuthenticateRequestAsync(BeginEventHandler beginHandler, EndEventHandler endHandler, object state);
[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
public void AddOnPostAuthorizeRequestAsync(BeginEventHandler bh, EndEventHandler eh);
public void AddOnPostAuthorizeRequestAsync(BeginEventHandler beginHandler, EndEventHandler endHandler, object state);
public void AddOnPostLogRequestAsync(BeginEventHandler bh, EndEventHandler eh);
public void AddOnPostLogRequestAsync(BeginEventHandler beginHandler, EndEventHandler endHandler, object state);
[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
public void AddOnPostMapRequestHandlerAsync(BeginEventHandler bh, EndEventHandler eh);
public void AddOnPostMapRequestHandlerAsync(BeginEventHandler beginHandler, EndEventHandler endHandler, object state);
[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
public void AddOnPostReleaseRequestStateAsync(BeginEventHandler bh, EndEventHandler eh);
public void AddOnPostReleaseRequestStateAsync(BeginEventHandler beginHandler, EndEventHandler endHandler, object state);
[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
public void AddOnPostRequestHandlerExecuteAsync(BeginEventHandler bh, EndEventHandler eh);
public void AddOnPostRequestHandlerExecuteAsync(BeginEventHandler beginHandler, EndEventHandler endHandler, object state);
[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
public void AddOnPostResolveRequestCacheAsync(BeginEventHandler bh, EndEventHandler eh);
public void AddOnPostResolveRequestCacheAsync(BeginEventHandler beginHandler, EndEventHandler endHandler, object state);
[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
public void AddOnPostUpdateRequestCacheAsync(BeginEventHandler bh, EndEventHandler eh);
public void AddOnPostUpdateRequestCacheAsync(BeginEventHandler beginHandler, EndEventHandler endHandler, object state);
[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
public void AddOnPreRequestHandlerExecuteAsync(BeginEventHandler bh, EndEventHandler eh);
public void AddOnPreRequestHandlerExecuteAsync(BeginEventHandler beginHandler, EndEventHandler endHandler, object state);
[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
public void AddOnReleaseRequestStateAsync(BeginEventHandler bh, EndEventHandler eh);
public void AddOnReleaseRequestStateAsync(BeginEventHandler beginHandler, EndEventHandler endHandler, object state);
[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
public void AddOnResolveRequestCacheAsync(BeginEventHandler bh, EndEventHandler eh);
public void AddOnResolveRequestCacheAsync(BeginEventHandler beginHandler, EndEventHandler endHandler, object state);
[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
public void AddOnUpdateRequestCacheAsync(BeginEventHandler bh, EndEventHandler eh);
public void AddOnUpdateRequestCacheAsync(BeginEventHandler beginHandler, EndEventHandler endHandler, object state);
private void AddSendResponseEventHookup(object key, Delegate handler);
[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
internal void AddSyncEventHookup(object key, Delegate handler, RequestNotification notification);
private void AddSyncEventHookup(object key, Delegate handler, RequestNotification notification, bool isPostNotification);
internal void AssignContext(HttpContext context);
internal IAsyncResult BeginProcessRequestNotification(HttpContext context, AsyncCallback cb);
private void BuildEventMaskDictionary(Dictionary<string, RequestNotification> eventMask);
private HttpModuleCollection BuildIntegratedModuleCollection(List<ModuleConfigurationInfo> moduleList);
internal void ClearError();
public void CompleteRequest();
private HttpModuleCollection CreateDynamicModules();
private void CreateEventExecutionSteps(object eventIndex, ArrayList steps);
internal IExecutionStep CreateImplicitAsyncPreloadExecutionStep();
public virtual void Dispose();
internal void DisposeInternal();
internal RequestNotificationStatus EndProcessRequestNotification(IAsyncResult result);
internal void EnsureReleaseState();
internal Exception ExecuteStep(IExecutionStep step, ref bool completedSynchronously);
private IEnumerable<ModuleConfigurationInfo> GetConfigInfoForDynamicModules();
[SecurityPermission(SecurityAction.Assert, ControlPrincipal=true)]
internal static WindowsIdentity GetCurrentWindowsIdentityWithAssert();
private IHttpHandlerFactory GetFactory(string type);
private IHttpHandlerFactory GetFactory(HttpHandlerAction mapping);
internal static string GetFallbackCulture(string culture);
private HttpHandlerAction GetHandlerMapping(HttpContext context, string requestType, VirtualPath path, bool useAppConfig);
private HttpModuleCollection GetModuleCollection(IntPtr appContext);
private PipelineModuleStepContainer GetModuleContainer(string moduleName);
public virtual string GetOutputCacheProviderName(HttpContext context);
public virtual string GetVaryByCustomString(HttpContext context, string custom);
private bool HasEventSubscription(object eventIndex);
private void HookupEventHandlersForApplicationAndModules(MethodInfo[] handlers);
public virtual void Init();
private void InitAppLevelCulture();
private void InitIntegratedModules();
internal void InitInternal(HttpContext context, HttpApplicationState state, MethodInfo[] handlers);
private void InitModules();
private void InitModulesCommon();
internal void InitSpecial(HttpApplicationState state, MethodInfo[] handlers, IntPtr appContext, HttpContext context);
[ReflectionPermission(SecurityAction.Assert, Flags=ReflectionPermissionFlag.RestrictedMemberAccess)]
private void InvokeMethodWithAssert(MethodInfo method, int paramCount, object eventSource, EventArgs eventArgs);
internal IHttpHandler MapHttpHandler(HttpContext context, string requestType, VirtualPath path, string pathTranslated, bool useAppConfig);
internal IHttpHandler MapIntegratedHttpHandler(HttpContext context, string requestType, VirtualPath path, string pathTranslated, bool useAppConfig, bool convertNativeStaticFileModule);
[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
internal ThreadContext OnThreadEnter();
[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
internal ThreadContext OnThreadEnter(bool setImpersonationContext);
private ThreadContext OnThreadEnterPrivate(bool setImpersonationContext);
private void ProcessEventSubscriptions(out RequestNotification requestNotifications, out RequestNotification postRequestNotifications);
internal void ProcessSpecialRequest(HttpContext context, MethodInfo method, int paramCount, object eventSource, EventArgs eventArgs, HttpSessionState session);
internal void RaiseErrorWithoutContext(Exception error);
private void RaiseOnError();
internal void RaiseOnPreSendRequestContent();
internal void RaiseOnPreSendRequestHeaders();
private void RaiseOnRequestCompleted();
private void RecordError(Exception error);
private void RecycleHandlers();
private void RegisterEventSubscriptionsWithIIS(IntPtr appContext, HttpContext context, MethodInfo[] handlers);
private void RegisterIntegratedEvent(IntPtr appContext, string moduleName, RequestNotification requestNotifications, RequestNotification postRequestNotifications, string moduleType, string modulePrecondition, bool useHighPriority);
public static void RegisterModule(Type moduleType);
internal static void RegisterModuleInternal(Type moduleType);
internal void ReleaseAppInstance();
internal void ReleaseNotifcationContextLock();
private void RemoveSendResponseEventHookup(object key, Delegate handler);
[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
internal void RemoveSyncEventHookup(object key, Delegate handler, RequestNotification notification);
internal void RemoveSyncEventHookup(object key, Delegate handler, RequestNotification notification, bool isPostNotification);
private void RestoreAppLevelCulture();
private void ResumeSteps(Exception error);
private void ResumeStepsFromThreadPoolThread(Exception error);
private void ResumeStepsWaitCallback(object error);
private void SetAppLevelCulture();
[SecurityPermission(SecurityAction.Assert, ControlPrincipal=true)]
internal static void SetCurrentPrincipalWithAssert(IPrincipal user);
IAsyncResult IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData);
void IHttpAsyncHandler.EndProcessRequest(IAsyncResult result);
void IHttpHandler.ProcessRequest(HttpContext context);
[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
ISyncContextLock ISyncContext.Enter();
private void ThrowIfEventBindingDisallowed(); // Properties
internal EventArgs AppEvent { get; set; }
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), Browsable(false)]
public HttpApplicationState Application { [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] get; }
private AsyncAppEventHandlersTable AsyncEvents { get; }
internal HttpAsyncResult AsyncResult { get; set; }
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), Browsable(false)]
public HttpContext Context { get; }
internal string CurrentModuleCollectionKey { get; }
private PipelineModuleStepContainer CurrentModuleContainer { get; }
internal byte[] EntityBuffer { get; }
protected EventHandlerList Events { get; }
internal static List<ModuleConfigurationInfo> IntegratedModuleList { [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] get; }
private bool IsContainerInitalizationAllowed { get; }
internal bool IsRequestCompleted { get; }
internal Exception LastError { get; }
private PipelineModuleStepContainer[] ModuleContainers { get; }
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public HttpModuleCollection Modules { [AspNetHostingPermission(SecurityAction.Demand, Level=AspNetHostingPermissionLevel.High)] get; }
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), Browsable(false)]
public HttpRequest Request { get; }
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public HttpResponse Response { get; }
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), Browsable(false)]
public HttpServerUtility Server { get; }
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public HttpSessionState Session { get; }
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public ISite Site { [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] get; [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] set; }
bool IHttpHandler.IsReusable { get; }
bool IRequestCompletedNotifier.IsRequestCompleted { [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] get; }
HttpContext ISyncContext.HttpContext { get; }
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public IPrincipal User { get; } // Nested Types
internal class ApplicationStepManager : HttpApplication.StepManager
{
// Fields
private int _currentStepIndex;
private int _endRequestStepIndex;
private HttpApplication.IExecutionStep[] _execSteps;
private int _numStepCalls;
private int _numSyncStepCalls;
private WaitCallback _resumeStepsWaitCallback; // Methods
[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
internal ApplicationStepManager(HttpApplication app);
internal override void BuildSteps(WaitCallback stepCallback);
internal override void InitRequest();
[DebuggerStepperBoundary]
internal override void ResumeSteps(Exception error);
} internal class AsyncAppEventHandler
{
// Fields
private ArrayList _beginHandlers;
private int _count;
private ArrayList _endHandlers;
private ArrayList _stateObjects; // Methods
internal AsyncAppEventHandler();
internal void Add(BeginEventHandler beginHandler, EndEventHandler endHandler, object state);
internal void CreateExecutionSteps(HttpApplication app, ArrayList steps);
internal void Reset(); // Properties
internal int Count { [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] get; }
} internal class AsyncAppEventHandlersTable
{
// Fields
private Hashtable _table; // Methods
[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
public AsyncAppEventHandlersTable();
internal void AddHandler(object eventId, BeginEventHandler beginHandler, EndEventHandler endHandler, object state, RequestNotification requestNotification, bool isPost, HttpApplication app); // Properties
internal HttpApplication.AsyncAppEventHandler this[object eventId] { get; }
} internal class AsyncEventExecutionStep : HttpApplication.IExecutionStep
{
// Fields
private HttpApplication _application;
private HttpApplication.AsyncStepCompletionInfo _asyncStepCompletionInfo;
private BeginEventHandler _beginHandler;
private AsyncCallback _completionCallback;
private EndEventHandler _endHandler;
private object _state;
private bool _sync;
private string _targetTypeStr; // Methods
internal AsyncEventExecutionStep(HttpApplication app, BeginEventHandler beginHandler, EndEventHandler endHandler, object state);
internal AsyncEventExecutionStep(HttpApplication app, BeginEventHandler beginHandler, EndEventHandler endHandler, object state, bool useIntegratedPipeline);
private void OnAsyncEventCompletion(IAsyncResult ar);
private void ResumeSteps(Exception error);
[PermissionSet(SecurityAction.Assert, Unrestricted=true)]
private void ResumeStepsWithAssert(Exception error);
void HttpApplication.IExecutionStep.Execute(); // Properties
bool HttpApplication.IExecutionStep.CompletedSynchronously { get; }
bool HttpApplication.IExecutionStep.IsCancellable { get; }
} [StructLayout(LayoutKind.Sequential)]
private struct AsyncStepCompletionInfo
{
private volatile int _asyncState;
private ExceptionDispatchInfo _error;
private const int ASYNC_STATE_NONE = ;
private const int ASYNC_STATE_BEGIN_UNWOUND = ;
private const int ASYNC_STATE_CALLBACK_COMPLETED = ;
public bool RegisterAsyncCompletion(Exception error);
public void RegisterBeginUnwound(IAsyncResult asyncResult, out bool operationCompleted, out bool mustCallEndHandler);
public void ReportError();
public void Reset();
} internal class CallFilterExecutionStep : HttpApplication.IExecutionStep
{
// Fields
private HttpApplication _application; // Methods
[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
internal CallFilterExecutionStep(HttpApplication app);
void HttpApplication.IExecutionStep.Execute(); // Properties
bool HttpApplication.IExecutionStep.CompletedSynchronously { get; }
bool HttpApplication.IExecutionStep.IsCancellable { get; }
} internal class CallHandlerExecutionStep : HttpApplication.IExecutionStep
{
// Fields
private HttpApplication _application;
private HttpApplication.AsyncStepCompletionInfo _asyncStepCompletionInfo;
private AsyncCallback _completionCallback;
private IHttpAsyncHandler _handler;
private bool _sync; // Methods
internal CallHandlerExecutionStep(HttpApplication app);
private void OnAsyncHandlerCompletion(IAsyncResult ar);
private void ResumeSteps(Exception error);
[PermissionSet(SecurityAction.Assert, Unrestricted=true)]
private void ResumeStepsWithAssert(Exception error);
private static void SuppressPostEndRequestIfNecessary(HttpContext context);
void HttpApplication.IExecutionStep.Execute(); // Properties
bool HttpApplication.IExecutionStep.CompletedSynchronously { get; }
bool HttpApplication.IExecutionStep.IsCancellable { get; }
} internal class CancelModuleException
{
// Fields
private bool _timeout; // Methods
[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
internal CancelModuleException(bool timeout); // Properties
internal bool Timeout { [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] get; }
} internal interface IExecutionStep
{
// Methods
void Execute(); // Properties
bool CompletedSynchronously { get; }
bool IsCancellable { get; }
} internal class MapHandlerExecutionStep : HttpApplication.IExecutionStep
{
// Fields
private HttpApplication _application; // Methods
[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
internal MapHandlerExecutionStep(HttpApplication app);
void HttpApplication.IExecutionStep.Execute(); // Properties
bool HttpApplication.IExecutionStep.CompletedSynchronously { get; }
bool HttpApplication.IExecutionStep.IsCancellable { get; }
} internal class MaterializeHandlerExecutionStep : HttpApplication.IExecutionStep
{
// Fields
private HttpApplication _application; // Methods
[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
internal MaterializeHandlerExecutionStep(HttpApplication app);
void HttpApplication.IExecutionStep.Execute(); // Properties
bool HttpApplication.IExecutionStep.CompletedSynchronously { get; }
bool HttpApplication.IExecutionStep.IsCancellable { get; }
} internal class NoopExecutionStep : HttpApplication.IExecutionStep
{
// Methods
[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
internal NoopExecutionStep();
void HttpApplication.IExecutionStep.Execute(); // Properties
bool HttpApplication.IExecutionStep.CompletedSynchronously { get; }
bool HttpApplication.IExecutionStep.IsCancellable { get; }
} internal class PipelineStepManager : HttpApplication.StepManager
{
// Fields
private WaitCallback _resumeStepsWaitCallback;
private bool _validateInputCalled;
private bool _validatePathCalled; // Methods
[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
internal PipelineStepManager(HttpApplication app);
internal override void BuildSteps(WaitCallback stepCallback);
internal override void InitRequest();
[DebuggerStepperBoundary]
internal override void ResumeSteps(Exception error);
private Exception ValidateHelper(HttpContext context);
} internal class SendResponseExecutionStep : HttpApplication.IExecutionStep
{
// Fields
private HttpApplication _application;
private EventHandler _handler;
private bool _isHeaders; // Methods
[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
internal SendResponseExecutionStep(HttpApplication app, EventHandler handler, bool isHeaders);
void HttpApplication.IExecutionStep.Execute(); // Properties
bool HttpApplication.IExecutionStep.CompletedSynchronously { get; }
bool HttpApplication.IExecutionStep.IsCancellable { get; }
} internal abstract class StepManager
{
// Fields
protected HttpApplication _application;
protected bool _requestCompleted; // Methods
[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
internal StepManager(HttpApplication application);
internal abstract void BuildSteps(WaitCallback stepCallback);
internal void CompleteRequest();
internal abstract void InitRequest();
internal abstract void ResumeSteps(Exception error); // Properties
internal bool IsCompleted { [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] get; }
} internal class SyncEventExecutionStep : HttpApplication.IExecutionStep
{
// Fields
private HttpApplication _application;
private EventHandler _handler; // Methods
[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
internal SyncEventExecutionStep(HttpApplication app, EventHandler handler);
void HttpApplication.IExecutionStep.Execute(); // Properties
internal EventHandler Handler { [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] get; }
bool HttpApplication.IExecutionStep.CompletedSynchronously { [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")] get; }
bool HttpApplication.IExecutionStep.IsCancellable { [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")] get; }
} internal class TransitionToWebSocketsExecutionStep : HttpApplication.IExecutionStep
{
// Fields
private readonly HttpApplication _application; // Methods
[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
internal TransitionToWebSocketsExecutionStep(HttpApplication app);
void HttpApplication.IExecutionStep.Execute(); // Properties
public bool CompletedSynchronously { [CompilerGenerated, TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] get; [CompilerGenerated] private set; }
public bool IsCancellable { get; }
} internal class UrlMappingsExecutionStep : HttpApplication.IExecutionStep
{
// Fields
private HttpApplication _application; // Methods
[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
internal UrlMappingsExecutionStep(HttpApplication app);
void HttpApplication.IExecutionStep.Execute(); // Properties
bool HttpApplication.IExecutionStep.CompletedSynchronously { get; }
bool HttpApplication.IExecutionStep.IsCancellable { get; }
} internal class ValidatePathExecutionStep : HttpApplication.IExecutionStep
{
// Fields
private HttpApplication _application; // Methods
[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
internal ValidatePathExecutionStep(HttpApplication app);
void HttpApplication.IExecutionStep.Execute(); // Properties
bool HttpApplication.IExecutionStep.CompletedSynchronously { get; }
bool HttpApplication.IExecutionStep.IsCancellable { get; }
} internal class ValidateRequestExecutionStep : HttpApplication.IExecutionStep
{
// Fields
private HttpApplication _application; // Methods
[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
internal ValidateRequestExecutionStep(HttpApplication app);
void HttpApplication.IExecutionStep.Execute(); // Properties
bool HttpApplication.IExecutionStep.CompletedSynchronously { get; }
bool HttpApplication.IExecutionStep.IsCancellable { get; }
}
} Expand Methods
感兴趣的可以看一下这里面的属性,事件(事件执行顺序并不是写的那个顺序);下面我画张图,简单描述一下过程

ASP.NET 运行机制

剩下就是页面类执行ProcessRequest的方法了,今天先不说了,太晚了。接下来我们继续mvc也可以了,我们mvc并没有页面类的ProcessRequest方法,以后有时间在说这里吧。