原本今天打算继续写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程序集下的类

  1. public sealed class ISAPIRuntime : MarshalByRefObject, IISAPIRuntime, IISAPIRuntime2, IRegisteredObject
  2. {
  3. // Fields
  4. private static int _isThisAppDomainRemovedFromUnmanagedTable;
  5. private const int WORKER_REQUEST_TYPE_IN_PROC = ;
  6. private const int WORKER_REQUEST_TYPE_IN_PROC_VERSION_2 = ;
  7. private const int WORKER_REQUEST_TYPE_OOP = ;
  8.  
  9. // Methods
  10. [SecurityPermission(SecurityAction.Demand, Unrestricted=true)]
  11. public ISAPIRuntime();
  12. [SecurityPermission(SecurityAction.LinkDemand, Unrestricted=true)]
  13. public void DoGCCollect();
  14. public override object InitializeLifetimeService();
  15. [SecurityPermission(SecurityAction.LinkDemand, Unrestricted=true)]
  16. public int ProcessRequest(IntPtr ecb, int iWRType);
  17. internal static void RemoveThisAppDomainFromUnmanagedTable();
  18. [SecurityPermission(SecurityAction.LinkDemand, Unrestricted=true)]
  19. public void StartProcessing();
  20. [SecurityPermission(SecurityAction.LinkDemand, Unrestricted=true)]
  21. public void StopProcessing();
  22. [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
  23. void IISAPIRuntime2.DoGCCollect();
  24. [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
  25. int IISAPIRuntime2.ProcessRequest(IntPtr ecb, int iWRType);
  26. [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
  27. void IISAPIRuntime2.StartProcessing();
  28. [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
  29. void IISAPIRuntime2.StopProcessing();
  30. void IRegisteredObject.Stop(bool immediate);
  31. }
  32.  
  33. 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方法的内容

  1. [SecurityPermission(SecurityAction.LinkDemand, Unrestricted=true)]
  2. public int ProcessRequest(IntPtr ecb, int iWRType)
  3. {
  4. IntPtr zero = IntPtr.Zero;
  5. if (iWRType == )
  6. {
  7. zero = ecb;
  8. ecb = UnsafeNativeMethods.GetEcb(zero);
  9. }
  10. ISAPIWorkerRequest wr = null;
  11. try
  12. {
  13. bool useOOP = iWRType == ;
  14. wr = ISAPIWorkerRequest.CreateWorkerRequest(ecb, useOOP);
  15. wr.Initialize();
  16. string appPathTranslated = wr.GetAppPathTranslated();
  17. string appDomainAppPathInternal = HttpRuntime.AppDomainAppPathInternal;
  18. if ((appDomainAppPathInternal == null) || StringUtil.EqualsIgnoreCase(appPathTranslated, appDomainAppPathInternal))
  19. {
  20. HttpRuntime.ProcessRequestNoDemand(wr);
  21. return ;
  22. }
  23. HttpRuntime.ShutdownAppDomain(ApplicationShutdownReason.PhysicalApplicationPathChanged, SR.GetString("Hosting_Phys_Path_Changed", new object[] { appDomainAppPathInternal, appPathTranslated }));
  24. return ;
  25. }
  26. catch (Exception exception)
  27. {
  28. try
  29. {
  30. WebBaseEvent.RaiseRuntimeError(exception, this);
  31. }
  32. catch
  33. {
  34. }
  35. if ((wr == null) || !(wr.Ecb == IntPtr.Zero))
  36. {
  37. throw;
  38. }
  39. if (zero != IntPtr.Zero)
  40. {
  41. UnsafeNativeMethods.SetDoneWithSessionCalled(zero);
  42. }
  43. if (exception is ThreadAbortException)
  44. {
  45. Thread.ResetAbort();
  46. }
  47. return ;
  48. }
  49. }

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

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

  1. internal static void ProcessRequestNoDemand(HttpWorkerRequest wr)
  2. {
  3. RequestQueue queue = _theRuntime._requestQueue;
  4. wr.UpdateInitialCounters();
  5. if (queue != null)
  6. {
  7. wr = queue.GetRequestToExecute(wr);
  8. }
  9. if (wr != null)
  10. {
  11. CalculateWaitTimeAndUpdatePerfCounter(wr);
  12. wr.ResetStartTime();
  13. ProcessRequestNow(wr);
  14. }
  15. }

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

  1. internal HttpWorkerRequest GetRequestToExecute(HttpWorkerRequest wr)
  2. {
  3. int num;
  4. int num2;
  5. int num3;
  6. ThreadPool.GetAvailableThreads(out num, out num2);
  7. if (this._iis6)
  8. {
  9. num3 = num;
  10. }
  11. else
  12. {
  13. num3 = (num2 > num) ? num : num2;
  14. }
  15. if ((num3 < this._minExternFreeThreads) || (this._count != ))
  16. {
  17. bool isLocal = IsLocal(wr);
  18. if ((isLocal && (num3 >= this._minLocalFreeThreads)) && (this._count == ))
  19. {
  20. return wr;
  21. }
  22. if (this._count >= this._queueLimit)
  23. {
  24. HttpRuntime.RejectRequestNow(wr, false);
  25. return null;
  26. }
  27. this.QueueRequest(wr, isLocal);
  28. if (num3 >= this._minExternFreeThreads)
  29. {
  30. wr = this.DequeueRequest(false);
  31. return wr;
  32. }
  33. if (num3 >= this._minLocalFreeThreads)
  34. {
  35. wr = this.DequeueRequest(true);
  36. return wr;
  37. }
  38. wr = null;
  39. this.ScheduleMoreWorkIfNeeded();
  40. }
  41. return wr;
  42. }

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

  1. internal static void ProcessRequestNow(HttpWorkerRequest wr)
  2. {
  3. _theRuntime.ProcessRequestInternal(wr);
  4. }

我们只看ProcessRequestNow()方法

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

  1. public sealed class HttpRuntime
  2. {
  3. // Fields
  4. private int _activeRequestCount;
  5. private bool _apartmentThreading;
  6. private string _appDomainAppId;
  7. private string _appDomainAppPath;
  8. private VirtualPath _appDomainAppVPath;
  9. private string _appDomainId;
  10. private Timer _appDomainShutdownTimer;
  11. private WaitCallback _appDomainUnloadallback;
  12. private byte[] _appOfflineMessage;
  13. private HttpWorkerRequest.EndOfSendNotification _asyncEndOfSendCallback;
  14. private bool _beforeFirstRequest;
  15. private CacheInternal _cacheInternal;
  16. private Cache _cachePublic;
  17. private string _clientScriptPhysicalPath;
  18. private string _clientScriptVirtualPath;
  19. private string _codegenDir;
  20. private bool _configInited;
  21. private bool _debuggingEnabled;
  22. private static string _DefaultPhysicalPathOnMapPathFailure;
  23. private bool _disableProcessRequestInApplicationTrust;
  24. private volatile bool _disposingHttpRuntime;
  25. private bool _enableHeaderChecking;
  26. private static bool _enablePrefetchOptimization;
  27. private FileChangesMonitor _fcm;
  28. private bool _firstRequestCompleted;
  29. private DateTime _firstRequestStartTime;
  30. private bool _fusionInited;
  31. private AsyncCallback _handlerCompletionCallback;
  32. private bool _hostingInitFailed;
  33. private string _hostSecurityPolicyResolverType;
  34. private static Version _iisVersion;
  35. private Exception _initializationError;
  36. private bool _isLegacyCas;
  37. private bool _isOnUNCShare;
  38. private DateTime _lastShutdownAttemptTime;
  39. private NamedPermissionSet _namedPermissionSet;
  40. private PolicyLevel _policyLevel;
  41. private bool _processRequestInApplicationTrust;
  42. private Profiler _profiler;
  43. private AsyncCallback _requestNotificationCompletionCallback;
  44. private RequestQueue _requestQueue;
  45. private bool _shutdownInProgress;
  46. private string _shutDownMessage;
  47. private ApplicationShutdownReason _shutdownReason;
  48. private string _shutDownStack;
  49. private bool _shutdownWebEventRaised;
  50. private string _tempDir;
  51. private static HttpRuntime _theRuntime;
  52. private RequestTimeoutManager _timeoutManager;
  53. private string _trustLevel;
  54. private static bool _useIntegratedPipeline;
  55. private bool _userForcedShutdown;
  56. private string _wpUserId;
  57. private static BuildManagerHostUnloadEventHandler AppDomainShutdown;
  58. private const string AppOfflineFileName = "App_Offline.htm";
  59. private const string AspNetClientFilesParentVirtualPath = "/aspnet_client/system_web/";
  60. private const string AspNetClientFilesSubDirectory = "asp.netclientfiles";
  61. internal const string BinDirectoryName = "bin";
  62. internal const string BrowsersDirectoryName = "App_Browsers";
  63. internal const string CodeDirectoryName = "App_Code";
  64. internal const string codegenDirName = "Temporary ASP.NET Files";
  65. internal const string DataDirectoryName = "App_Data";
  66. private static string DirectorySeparatorString;
  67. private static string DoubleDirectorySeparatorString;
  68. internal const string GlobalThemesDirectoryName = "Themes";
  69. internal const string LocalResourcesDirectoryName = "App_LocalResources";
  70. private const long MaxAppOfflineFileLength = 0x100000L;
  71. internal const string profileFileName = "profileoptimization.prof";
  72. internal const string ResourcesDirectoryName = "App_GlobalResources";
  73. internal static byte[] s_autogenKeys;
  74. private static Hashtable s_factoryCache;
  75. private static FactoryGenerator s_factoryGenerator;
  76. private static object s_factoryLock;
  77. private static bool s_initialized;
  78. private static bool s_initializedFactory;
  79. private static string s_installDirectory;
  80. private static char[] s_InvalidPhysicalPathChars;
  81. private static bool s_isEngineLoaded;
  82. internal const string ThemesDirectoryName = "App_Themes";
  83. internal const string WebRefDirectoryName = "App_WebReferences";
  84.  
  85. // Events
  86. internal static event BuildManagerHostUnloadEventHandler AppDomainShutdown;
  87.  
  88. // Methods
  89. static HttpRuntime();
  90. [SecurityPermission(SecurityAction.LinkDemand, Unrestricted=true)]
  91. public HttpRuntime();
  92. internal static void AddAppDomainTraceMessage(string message);
  93. private void AppDomainShutdownTimerCallback(object state);
  94. private static void CalculateWaitTimeAndUpdatePerfCounter(HttpWorkerRequest wr);
  95. [FileIOPermission(SecurityAction.Assert, Unrestricted=true)]
  96. private void CheckAccessToTempDirectory();
  97. internal static void CheckApplicationEnabled();
  98. internal static void CheckAspNetHostingPermission(AspNetHostingPermissionLevel level, string errorMessageId);
  99. [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
  100. internal static void CheckFilePermission(string path);
  101. internal static void CheckFilePermission(string path, bool writePermissions);
  102. internal static void CheckVirtualFilePermission(string virtualPath);
  103. [SecurityPermission(SecurityAction.Demand, Unrestricted=true)]
  104. public static void Close();
  105. internal static void CoalesceNotifications();
  106. private void CreateCache();
  107. [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
  108. internal static object CreateNonPublicInstance(Type type);
  109. [PermissionSet(SecurityAction.Assert, Unrestricted=true)]
  110. internal static object CreateNonPublicInstance(Type type, object[] args);
  111. private static PolicyLevel CreatePolicyLevel(string configFile, string appDir, string binDir, string strOriginUrl, out bool foundGacToken);
  112. internal static object CreatePublicInstance(Type type);
  113. internal static object CreatePublicInstance(Type type, object[] args);
  114. internal static void DecrementActivePipelineCount();
  115. private void Dispose();
  116. private void DisposeAppDomainShutdownTimer();
  117. private void EndOfSendCallback(HttpWorkerRequest wr, object arg);
  118. private void EnsureAccessToApplicationDirectory();
  119. private void EnsureFirstRequestInit(HttpContext context);
  120. internal static void FailIfNoAPTCABit(Type t, XmlNode node);
  121. internal static void FailIfNoAPTCABit(Type t, ElementInformation elemInfo, string propertyName);
  122. internal static object FastCreatePublicInstance(Type type);
  123. internal static void FinishPipelineRequest(HttpContext context);
  124. private void FinishRequest(HttpWorkerRequest wr, HttpContext context, Exception e);
  125. private void FinishRequestNotification(IIS7WorkerRequest wr, HttpContext context, ref RequestNotificationStatus status);
  126. private void FirstRequestInit(HttpContext context);
  127. internal static void ForceStaticInit();
  128. private static string GetAppDomainString(string key);
  129. internal static CacheInternal GetCacheInternal(bool createIfDoesNotExist);
  130. private static string GetCurrentUserName();
  131. internal static string GetGacLocation();
  132. private void GetInitConfigSections(out CacheSection cacheSection, out TrustSection trustSection, out SecurityPolicySection securityPolicySection, out CompilationSection compilationSection, out HostingEnvironmentSection hostingEnvironmentSection, out Exception initException);
  133. [AspNetHostingPermission(SecurityAction.Demand, Level=AspNetHostingPermissionLevel.Unrestricted)]
  134. public static NamedPermissionSet GetNamedPermissionSet();
  135. internal static string GetRelaxedMapPathResult(string originalResult);
  136. internal static string GetSafePath(string path);
  137. internal static bool HasAppPathDiscoveryPermission();
  138. private static bool HasAPTCABit(Assembly assembly);
  139. internal static bool HasAspNetHostingPermission(AspNetHostingPermissionLevel level);
  140. internal static bool HasDbPermission(DbProviderFactory factory);
  141. [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
  142. internal static bool HasFilePermission(string path);
  143. internal static bool HasFilePermission(string path, bool writePermissions);
  144. internal static bool HasPathDiscoveryPermission(string path);
  145. internal static bool HasUnmanagedPermission();
  146. internal static bool HasWebPermission(Uri uri);
  147. private void HostingInit(HostingEnvironmentFlags hostingFlags, PolicyLevel policyLevel, Exception appDomainCreationException);
  148. internal static void IncrementActivePipelineCount();
  149. private void Init();
  150. private void InitApartmentThreading();
  151. private void InitDebuggingSupport();
  152. private void InitFusion(HostingEnvironmentSection hostingEnvironmentSection);
  153. private void InitHeaderEncoding();
  154. private static void InitHttpConfiguration();
  155. private void InitializeHealthMonitoring();
  156. internal static void InitializeHostingFeatures(HostingEnvironmentFlags hostingFlags, PolicyLevel policyLevel, Exception appDomainCreationException);
  157. private bool InitiateShutdownOnce();
  158. private void InitRequestQueue();
  159. private void InitTrace(HttpContext context);
  160. internal static bool IsPathWithinAppRoot(string path);
  161. internal static bool IsTypeAccessibleFromPartialTrust(Type t);
  162. internal static bool IsTypeAllowedInConfig(Type t);
  163. internal static string MakeFileUrl(string path);
  164. internal static void OnAppDomainShutdown(BuildManagerHostUnloadEventArgs e);
  165. private void OnAppOfflineFileChange(object sender, FileChangeEvent e);
  166. internal static void OnConfigChange(string message);
  167. private void OnCriticalDirectoryChange(object sender, FileChangeEvent e);
  168. private void OnHandlerCompletion(IAsyncResult ar);
  169. private void OnRequestNotificationCompletion(IAsyncResult ar);
  170. private void OnRequestNotificationCompletionHelper(IAsyncResult ar);
  171. private void OnSecurityPolicyFileChange(object sender, FileChangeEvent e);
  172. internal static void PopulateIISVersionInformation();
  173. [PermissionSet(SecurityAction.Assert, Unrestricted=true)]
  174. private void PreloadAssembliesFromBin();
  175. private void PreloadAssembliesFromBinRecursive(DirectoryInfo dirInfo);
  176. [AspNetHostingPermission(SecurityAction.Demand, Level=AspNetHostingPermissionLevel.Medium)]
  177. public static void ProcessRequest(HttpWorkerRequest wr);
  178. private void ProcessRequestInternal(HttpWorkerRequest wr);
  179. internal static void ProcessRequestNoDemand(HttpWorkerRequest wr);
  180. internal static RequestNotificationStatus ProcessRequestNotification(IIS7WorkerRequest wr, HttpContext context);
  181. private RequestNotificationStatus ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context);
  182. internal static void ProcessRequestNow(HttpWorkerRequest wr);
  183. private void RaiseShutdownWebEventOnce();
  184. internal static void RecoverFromUnexceptedAppDomainUnload();
  185. private void RejectRequestInternal(HttpWorkerRequest wr, bool silent);
  186. internal static void RejectRequestNow(HttpWorkerRequest wr, bool silent);
  187. private void RelaxMapPathIfRequired();
  188. [PermissionSet(SecurityAction.Assert, Unrestricted=true)]
  189. private void ReleaseResourcesAndUnloadAppDomain(object state);
  190. internal static void ReportAppOfflineErrorMessage(HttpResponse response, byte[] appOfflineMessage);
  191. internal static void RestrictIISFolders(HttpContext context);
  192. private void SetAutoConfigLimits(ProcessModelSection pmConfig);
  193. private static void SetAutogenKeys();
  194. [SecurityPermission(SecurityAction.Assert, ControlThread=true)]
  195. internal static void SetCurrentThreadCultureWithAssert(CultureInfo cultureInfo);
  196. private static void SetExecutionTimePerformanceCounter(HttpContext context);
  197. internal static void SetShutdownMessage(string message);
  198. internal static void SetShutdownReason(ApplicationShutdownReason reason, string message);
  199. private void SetThreadPoolLimits();
  200. private void SetTrustLevel(TrustSection trustSection, SecurityPolicySection securityPolicySection);
  201. private void SetTrustParameters(TrustSection trustSection, SecurityPolicySection securityPolicySection, PolicyLevel policyLevel);
  202. private void SetUpCodegenDirectory(CompilationSection compilationSection);
  203. private void SetUpDataDirectory();
  204. internal static void SetUserForcedShutdown();
  205. private static bool ShutdownAppDomain(string stackTrace);
  206. [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
  207. internal static bool ShutdownAppDomain(ApplicationShutdownReason reason, string message);
  208. internal static bool ShutdownAppDomainWithStackTrace(ApplicationShutdownReason reason, string message, string stackTrace);
  209. private void StartAppDomainShutdownTimer();
  210. internal static void StartListeningToLocalResourcesDirectory(VirtualPath virtualDir);
  211. private void StartMonitoringDirectoryRenamesAndBinDirectory();
  212. private static void StaticInit();
  213. public static void UnloadAppDomain();
  214. private static void UpdatePerfCounters(int statusCode);
  215. private void WaitForRequestsToFinish(int waitTimeoutMs);
  216.  
  217. // Properties
  218. internal static bool ApartmentThreading { get; }
  219. public static string AppDomainAppId { get; }
  220. public static string AppDomainAppPath { get; }
  221. internal static string AppDomainAppPathInternal { get; }
  222. public static string AppDomainAppVirtualPath { get; }
  223. internal static VirtualPath AppDomainAppVirtualPathObject { get; }
  224. internal static string AppDomainAppVirtualPathString { get; }
  225. public static string AppDomainId { [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries"), AspNetHostingPermission(SecurityAction.Demand, Level=AspNetHostingPermissionLevel.High)] get; }
  226. internal static string AppDomainIdInternal { get; }
  227. internal static byte[] AppOfflineMessage { get; }
  228. public static string AspClientScriptPhysicalPath { get; }
  229. internal static string AspClientScriptPhysicalPathInternal { get; }
  230. public static string AspClientScriptVirtualPath { get; }
  231. public static string AspInstallDirectory { get; }
  232. internal static string AspInstallDirectoryInternal { [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] get; }
  233. public static string BinDirectory { get; }
  234. internal static string BinDirectoryInternal { get; }
  235. public static Cache Cache { get; }
  236. internal static CacheInternal CacheInternal { [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] get; }
  237. public static string ClrInstallDirectory { get; }
  238. internal static string ClrInstallDirectoryInternal { get; }
  239. internal static VirtualPath CodeDirectoryVirtualPath { get; }
  240. public static string CodegenDir { get; }
  241. internal static string CodegenDirInternal { get; }
  242. internal static bool ConfigInited { get; }
  243. internal static bool DebuggingEnabled { get; }
  244. internal static bool DisableProcessRequestInApplicationTrust { get; }
  245. internal static bool EnableHeaderChecking { get; }
  246. internal static bool EnablePrefetchOptimization { [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] get; }
  247. internal static FileChangesMonitor FileChangesMonitor { get; }
  248. internal static bool FusionInited { get; }
  249. internal static bool HostingInitFailed { get; }
  250. internal static string HostSecurityPolicyResolverType { get; }
  251. public static Version IISVersion { [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] get; }
  252. internal static Exception InitializationException { get; set; }
  253. internal static bool IsAspNetAppDomain { get; }
  254. internal static bool IsEngineLoaded { [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] get; }
  255. internal static bool IsFullTrust { get; }
  256. internal static bool IsLegacyCas { get; }
  257. internal static bool IsMapPathRelaxed { get; }
  258. public static bool IsOnUNCShare { [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries"), AspNetHostingPermission(SecurityAction.Demand, Level=AspNetHostingPermissionLevel.Low)] get; }
  259. internal static bool IsOnUNCShareInternal { get; }
  260. internal static bool IsTrustLevelInitialized { get; }
  261. private DateTime LastShutdownAttemptTime { get; set; }
  262. public static string MachineConfigurationDirectory { get; }
  263. internal static string MachineConfigurationDirectoryInternal { get; }
  264. internal static NamedPermissionSet NamedPermissionSet { get; }
  265. internal static PolicyLevel PolicyLevel { get; }
  266. internal static bool ProcessRequestInApplicationTrust { get; }
  267. internal static Profiler Profile { get; }
  268. internal static RequestTimeoutManager RequestTimeoutManager { get; }
  269. internal static VirtualPath ResourcesDirectoryVirtualPath { get; }
  270. internal static bool ShutdownInProgress { get; }
  271. internal static ApplicationShutdownReason ShutdownReason { get; }
  272. public static Version TargetFramework { get; }
  273. internal static string TempDirInternal { get; }
  274. internal static string TrustLevel { get; }
  275. internal static bool UseIntegratedPipeline { [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")] get; }
  276. public static bool UsingIntegratedPipeline { [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] get; }
  277. internal static VirtualPath WebRefDirectoryVirtualPath { get; }
  278. internal static string WpUserId { get; }
  279. }
  280.  
  281. Expand Methods

看ProcessRequestInternal()方法

  1. private void ProcessRequestInternal(HttpWorkerRequest wr)
  2. {
  3. Interlocked.Increment(ref this._activeRequestCount);
  4. if (this._disposingHttpRuntime)
  5. {
  6. try
  7. {
  8. wr.SendStatus(0x1f7, "Server Too Busy");
  9. wr.SendKnownResponseHeader(, "text/html; charset=utf-8");
  10. byte[] bytes = Encoding.ASCII.GetBytes("<html><body>Server Too Busy</body></html>");
  11. wr.SendResponseFromMemory(bytes, bytes.Length);
  12. wr.FlushResponse(true);
  13. wr.EndOfRequest();
  14. }
  15. finally
  16. {
  17. Interlocked.Decrement(ref this._activeRequestCount);
  18. }
  19. }
  20. else
  21. {
  22. HttpContext context;
  23. try
  24. {
  25. context = new HttpContext(wr, false);
  26. }
  27. catch
  28. {
  29. try
  30. {
  31. wr.SendStatus(, "Bad Request");
  32. wr.SendKnownResponseHeader(, "text/html; charset=utf-8");
  33. byte[] data = Encoding.ASCII.GetBytes("<html><body>Bad Request</body></html>");
  34. wr.SendResponseFromMemory(data, data.Length);
  35. wr.FlushResponse(true);
  36. wr.EndOfRequest();
  37. return;
  38. }
  39. finally
  40. {
  41. Interlocked.Decrement(ref this._activeRequestCount);
  42. }
  43. }
  44. wr.SetEndOfSendNotification(this._asyncEndOfSendCallback, context);
  45. HostingEnvironment.IncrementBusyCount();
  46. try
  47. {
  48. try
  49. {
  50. this.EnsureFirstRequestInit(context);
  51. }
  52. catch
  53. {
  54. if (!context.Request.IsDebuggingRequest)
  55. {
  56. throw;
  57. }
  58. }
  59. context.Response.InitResponseWriter();
  60. IHttpHandler applicationInstance = HttpApplicationFactory.GetApplicationInstance(context);
  61. if (applicationInstance == null)
  62. {
  63. throw new HttpException(SR.GetString("Unable_create_app_object"));
  64. }
  65. if (EtwTrace.IsTraceEnabled(, ))
  66. {
  67. EtwTrace.Trace(EtwTraceType.ETW_TYPE_START_HANDLER, context.WorkerRequest, applicationInstance.GetType().FullName, "Start");
  68. }
  69. if (applicationInstance is IHttpAsyncHandler)
  70. {
  71. IHttpAsyncHandler handler2 = (IHttpAsyncHandler) applicationInstance;
  72. context.AsyncAppHandler = handler2;
  73. handler2.BeginProcessRequest(context, this._handlerCompletionCallback, context);
  74. }
  75. else
  76. {
  77. applicationInstance.ProcessRequest(context);
  78. this.FinishRequest(context.WorkerRequest, context, null);
  79. }
  80. }
  81. catch (Exception exception)
  82. {
  83. context.Response.InitResponseWriter();
  84. this.FinishRequest(wr, context, exception);
  85. }
  86. }
  87. }

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

  1. IHttpHandler applicationInstance = HttpApplicationFactory.GetApplicationInstance(context);使用HttpApplicationFactory创建HttpApplication对象,applicationInstance.ProcessRequest(context);在这个方法中会调用近20几个是事件,该对象在后面的事件中通过反射创建请求页面类的对象在第7个事件和第8个事件中间通过反射创建前台页面类对象,后续的事件之间又调用页面类对象的ProcessRequest方法,这就是我们写的asp.net程序后台类为什么有ProcessRequest方法了,我们应该知道前台页面类继承后台页面类,我在这里再贴一下HttpApplication类的代码
  1. [ToolboxItem(false)]
  2. public class HttpApplication : IComponent, IDisposable, IHttpAsyncHandler, IHttpHandler, IRequestCompletedNotifier, ISyncContext
  3. {
  4. // Fields
  5. private EventArgs _appEvent;
  6. private bool _appLevelAutoCulture;
  7. private bool _appLevelAutoUICulture;
  8. private CultureInfo _appLevelCulture;
  9. private CultureInfo _appLevelUICulture;
  10. private RequestNotification _appPostNotifications;
  11. private RequestNotification _appRequestNotifications;
  12. private HttpAsyncResult _ar;
  13. private AsyncAppEventHandlersTable _asyncEvents;
  14. private HttpContext _context;
  15. private string _currentModuleCollectionKey;
  16. private static readonly DynamicModuleRegistry _dynamicModuleRegistry;
  17. private byte[] _entityBuffer;
  18. private EventHandlerList _events;
  19. private Hashtable _handlerFactories;
  20. private ArrayList _handlerRecycleList;
  21. private bool _hideRequestResponse;
  22. private HttpContext _initContext;
  23. private bool _initInternalCompleted;
  24. private static bool _initSpecialCompleted;
  25. private Exception _lastError;
  26. private HttpModuleCollection _moduleCollection;
  27. private static List<ModuleConfigurationInfo> _moduleConfigInfo;
  28. private PipelineModuleStepContainer[] _moduleContainers;
  29. private static Hashtable _moduleIndexMap;
  30. private Dictionary<string, RequestNotification> _pipelineEventMasks;
  31. private WaitCallback _resumeStepsWaitCallback;
  32. private CultureInfo _savedAppLevelCulture;
  33. private CultureInfo _savedAppLevelUICulture;
  34. private HttpSessionState _session;
  35. private ISite _site;
  36. private HttpApplicationState _state;
  37. private StepManager _stepManager;
  38. private bool _timeoutManagerInitialized;
  39. internal CountdownTask ApplicationInstanceConsumersCounter;
  40. internal static readonly string AutoCulture;
  41. private static readonly object EventAcquireRequestState;
  42. private static readonly object EventAuthenticateRequest;
  43. private static readonly object EventAuthorizeRequest;
  44. private static readonly object EventBeginRequest;
  45. private static readonly object EventDefaultAuthentication;
  46. private static readonly object EventDisposed;
  47. private static readonly object EventEndRequest;
  48. private static readonly object EventErrorRecorded;
  49. private static readonly object EventLogRequest;
  50. private static readonly object EventMapRequestHandler;
  51. private static readonly object EventPostAcquireRequestState;
  52. private static readonly object EventPostAuthenticateRequest;
  53. private static readonly object EventPostAuthorizeRequest;
  54. private static readonly object EventPostLogRequest;
  55. private static readonly object EventPostMapRequestHandler;
  56. private static readonly object EventPostReleaseRequestState;
  57. private static readonly object EventPostRequestHandlerExecute;
  58. private static readonly object EventPostResolveRequestCache;
  59. private static readonly object EventPostUpdateRequestCache;
  60. private static readonly object EventPreRequestHandlerExecute;
  61. private static readonly object EventPreSendRequestContent;
  62. private static readonly object EventPreSendRequestHeaders;
  63. private static readonly object EventReleaseRequestState;
  64. private static readonly object EventRequestCompleted;
  65. private static readonly object EventResolveRequestCache;
  66. private static readonly object EventUpdateRequestCache;
  67. internal const string IMPLICIT_FILTER_MODULE = "AspNetFilterModule";
  68. internal const string IMPLICIT_HANDLER = "ManagedPipelineHandler";
  69. internal const string MANAGED_PRECONDITION = "managedHandler";
  70.  
  71. // Events
  72. public event EventHandler AcquireRequestState;
  73. public event EventHandler AuthenticateRequest;
  74. public event EventHandler AuthorizeRequest;
  75. public event EventHandler BeginRequest;
  76. internal event EventHandler DefaultAuthentication;
  77. public event EventHandler Disposed;
  78. public event EventHandler EndRequest;
  79. public event EventHandler Error;
  80. public event EventHandler LogRequest;
  81. public event EventHandler MapRequestHandler;
  82. public event EventHandler PostAcquireRequestState;
  83. public event EventHandler PostAuthenticateRequest;
  84. public event EventHandler PostAuthorizeRequest;
  85. public event EventHandler PostLogRequest;
  86. public event EventHandler PostMapRequestHandler;
  87. public event EventHandler PostReleaseRequestState;
  88. public event EventHandler PostRequestHandlerExecute;
  89. public event EventHandler PostResolveRequestCache;
  90. public event EventHandler PostUpdateRequestCache;
  91. public event EventHandler PreRequestHandlerExecute;
  92. public event EventHandler PreSendRequestContent;
  93. public event EventHandler PreSendRequestHeaders;
  94. public event EventHandler ReleaseRequestState;
  95. public event EventHandler RequestCompleted;
  96. public event EventHandler ResolveRequestCache;
  97. public event EventHandler UpdateRequestCache;
  98.  
  99. // Methods
  100. static HttpApplication();
  101. public HttpApplication();
  102. internal void AcquireNotifcationContextLock(ref bool locked);
  103. private void AddEventMapping(string moduleName, RequestNotification requestNotification, bool isPostNotification, IExecutionStep step);
  104. [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
  105. public void AddOnAcquireRequestStateAsync(BeginEventHandler bh, EndEventHandler eh);
  106. public void AddOnAcquireRequestStateAsync(BeginEventHandler beginHandler, EndEventHandler endHandler, object state);
  107. [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
  108. public void AddOnAuthenticateRequestAsync(BeginEventHandler bh, EndEventHandler eh);
  109. public void AddOnAuthenticateRequestAsync(BeginEventHandler beginHandler, EndEventHandler endHandler, object state);
  110. [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
  111. public void AddOnAuthorizeRequestAsync(BeginEventHandler bh, EndEventHandler eh);
  112. public void AddOnAuthorizeRequestAsync(BeginEventHandler beginHandler, EndEventHandler endHandler, object state);
  113. [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
  114. public void AddOnBeginRequestAsync(BeginEventHandler bh, EndEventHandler eh);
  115. public void AddOnBeginRequestAsync(BeginEventHandler beginHandler, EndEventHandler endHandler, object state);
  116. [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
  117. public void AddOnEndRequestAsync(BeginEventHandler bh, EndEventHandler eh);
  118. public void AddOnEndRequestAsync(BeginEventHandler beginHandler, EndEventHandler endHandler, object state);
  119. public void AddOnLogRequestAsync(BeginEventHandler bh, EndEventHandler eh);
  120. public void AddOnLogRequestAsync(BeginEventHandler beginHandler, EndEventHandler endHandler, object state);
  121. public void AddOnMapRequestHandlerAsync(BeginEventHandler bh, EndEventHandler eh);
  122. public void AddOnMapRequestHandlerAsync(BeginEventHandler beginHandler, EndEventHandler endHandler, object state);
  123. [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
  124. public void AddOnPostAcquireRequestStateAsync(BeginEventHandler bh, EndEventHandler eh);
  125. public void AddOnPostAcquireRequestStateAsync(BeginEventHandler beginHandler, EndEventHandler endHandler, object state);
  126. [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
  127. public void AddOnPostAuthenticateRequestAsync(BeginEventHandler bh, EndEventHandler eh);
  128. public void AddOnPostAuthenticateRequestAsync(BeginEventHandler beginHandler, EndEventHandler endHandler, object state);
  129. [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
  130. public void AddOnPostAuthorizeRequestAsync(BeginEventHandler bh, EndEventHandler eh);
  131. public void AddOnPostAuthorizeRequestAsync(BeginEventHandler beginHandler, EndEventHandler endHandler, object state);
  132. public void AddOnPostLogRequestAsync(BeginEventHandler bh, EndEventHandler eh);
  133. public void AddOnPostLogRequestAsync(BeginEventHandler beginHandler, EndEventHandler endHandler, object state);
  134. [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
  135. public void AddOnPostMapRequestHandlerAsync(BeginEventHandler bh, EndEventHandler eh);
  136. public void AddOnPostMapRequestHandlerAsync(BeginEventHandler beginHandler, EndEventHandler endHandler, object state);
  137. [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
  138. public void AddOnPostReleaseRequestStateAsync(BeginEventHandler bh, EndEventHandler eh);
  139. public void AddOnPostReleaseRequestStateAsync(BeginEventHandler beginHandler, EndEventHandler endHandler, object state);
  140. [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
  141. public void AddOnPostRequestHandlerExecuteAsync(BeginEventHandler bh, EndEventHandler eh);
  142. public void AddOnPostRequestHandlerExecuteAsync(BeginEventHandler beginHandler, EndEventHandler endHandler, object state);
  143. [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
  144. public void AddOnPostResolveRequestCacheAsync(BeginEventHandler bh, EndEventHandler eh);
  145. public void AddOnPostResolveRequestCacheAsync(BeginEventHandler beginHandler, EndEventHandler endHandler, object state);
  146. [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
  147. public void AddOnPostUpdateRequestCacheAsync(BeginEventHandler bh, EndEventHandler eh);
  148. public void AddOnPostUpdateRequestCacheAsync(BeginEventHandler beginHandler, EndEventHandler endHandler, object state);
  149. [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
  150. public void AddOnPreRequestHandlerExecuteAsync(BeginEventHandler bh, EndEventHandler eh);
  151. public void AddOnPreRequestHandlerExecuteAsync(BeginEventHandler beginHandler, EndEventHandler endHandler, object state);
  152. [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
  153. public void AddOnReleaseRequestStateAsync(BeginEventHandler bh, EndEventHandler eh);
  154. public void AddOnReleaseRequestStateAsync(BeginEventHandler beginHandler, EndEventHandler endHandler, object state);
  155. [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
  156. public void AddOnResolveRequestCacheAsync(BeginEventHandler bh, EndEventHandler eh);
  157. public void AddOnResolveRequestCacheAsync(BeginEventHandler beginHandler, EndEventHandler endHandler, object state);
  158. [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
  159. public void AddOnUpdateRequestCacheAsync(BeginEventHandler bh, EndEventHandler eh);
  160. public void AddOnUpdateRequestCacheAsync(BeginEventHandler beginHandler, EndEventHandler endHandler, object state);
  161. private void AddSendResponseEventHookup(object key, Delegate handler);
  162. [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
  163. internal void AddSyncEventHookup(object key, Delegate handler, RequestNotification notification);
  164. private void AddSyncEventHookup(object key, Delegate handler, RequestNotification notification, bool isPostNotification);
  165. internal void AssignContext(HttpContext context);
  166. internal IAsyncResult BeginProcessRequestNotification(HttpContext context, AsyncCallback cb);
  167. private void BuildEventMaskDictionary(Dictionary<string, RequestNotification> eventMask);
  168. private HttpModuleCollection BuildIntegratedModuleCollection(List<ModuleConfigurationInfo> moduleList);
  169. internal void ClearError();
  170. public void CompleteRequest();
  171. private HttpModuleCollection CreateDynamicModules();
  172. private void CreateEventExecutionSteps(object eventIndex, ArrayList steps);
  173. internal IExecutionStep CreateImplicitAsyncPreloadExecutionStep();
  174. public virtual void Dispose();
  175. internal void DisposeInternal();
  176. internal RequestNotificationStatus EndProcessRequestNotification(IAsyncResult result);
  177. internal void EnsureReleaseState();
  178. internal Exception ExecuteStep(IExecutionStep step, ref bool completedSynchronously);
  179. private IEnumerable<ModuleConfigurationInfo> GetConfigInfoForDynamicModules();
  180. [SecurityPermission(SecurityAction.Assert, ControlPrincipal=true)]
  181. internal static WindowsIdentity GetCurrentWindowsIdentityWithAssert();
  182. private IHttpHandlerFactory GetFactory(string type);
  183. private IHttpHandlerFactory GetFactory(HttpHandlerAction mapping);
  184. internal static string GetFallbackCulture(string culture);
  185. private HttpHandlerAction GetHandlerMapping(HttpContext context, string requestType, VirtualPath path, bool useAppConfig);
  186. private HttpModuleCollection GetModuleCollection(IntPtr appContext);
  187. private PipelineModuleStepContainer GetModuleContainer(string moduleName);
  188. public virtual string GetOutputCacheProviderName(HttpContext context);
  189. public virtual string GetVaryByCustomString(HttpContext context, string custom);
  190. private bool HasEventSubscription(object eventIndex);
  191. private void HookupEventHandlersForApplicationAndModules(MethodInfo[] handlers);
  192. public virtual void Init();
  193. private void InitAppLevelCulture();
  194. private void InitIntegratedModules();
  195. internal void InitInternal(HttpContext context, HttpApplicationState state, MethodInfo[] handlers);
  196. private void InitModules();
  197. private void InitModulesCommon();
  198. internal void InitSpecial(HttpApplicationState state, MethodInfo[] handlers, IntPtr appContext, HttpContext context);
  199. [ReflectionPermission(SecurityAction.Assert, Flags=ReflectionPermissionFlag.RestrictedMemberAccess)]
  200. private void InvokeMethodWithAssert(MethodInfo method, int paramCount, object eventSource, EventArgs eventArgs);
  201. internal IHttpHandler MapHttpHandler(HttpContext context, string requestType, VirtualPath path, string pathTranslated, bool useAppConfig);
  202. internal IHttpHandler MapIntegratedHttpHandler(HttpContext context, string requestType, VirtualPath path, string pathTranslated, bool useAppConfig, bool convertNativeStaticFileModule);
  203. [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
  204. internal ThreadContext OnThreadEnter();
  205. [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
  206. internal ThreadContext OnThreadEnter(bool setImpersonationContext);
  207. private ThreadContext OnThreadEnterPrivate(bool setImpersonationContext);
  208. private void ProcessEventSubscriptions(out RequestNotification requestNotifications, out RequestNotification postRequestNotifications);
  209. internal void ProcessSpecialRequest(HttpContext context, MethodInfo method, int paramCount, object eventSource, EventArgs eventArgs, HttpSessionState session);
  210. internal void RaiseErrorWithoutContext(Exception error);
  211. private void RaiseOnError();
  212. internal void RaiseOnPreSendRequestContent();
  213. internal void RaiseOnPreSendRequestHeaders();
  214. private void RaiseOnRequestCompleted();
  215. private void RecordError(Exception error);
  216. private void RecycleHandlers();
  217. private void RegisterEventSubscriptionsWithIIS(IntPtr appContext, HttpContext context, MethodInfo[] handlers);
  218. private void RegisterIntegratedEvent(IntPtr appContext, string moduleName, RequestNotification requestNotifications, RequestNotification postRequestNotifications, string moduleType, string modulePrecondition, bool useHighPriority);
  219. public static void RegisterModule(Type moduleType);
  220. internal static void RegisterModuleInternal(Type moduleType);
  221. internal void ReleaseAppInstance();
  222. internal void ReleaseNotifcationContextLock();
  223. private void RemoveSendResponseEventHookup(object key, Delegate handler);
  224. [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
  225. internal void RemoveSyncEventHookup(object key, Delegate handler, RequestNotification notification);
  226. internal void RemoveSyncEventHookup(object key, Delegate handler, RequestNotification notification, bool isPostNotification);
  227. private void RestoreAppLevelCulture();
  228. private void ResumeSteps(Exception error);
  229. private void ResumeStepsFromThreadPoolThread(Exception error);
  230. private void ResumeStepsWaitCallback(object error);
  231. private void SetAppLevelCulture();
  232. [SecurityPermission(SecurityAction.Assert, ControlPrincipal=true)]
  233. internal static void SetCurrentPrincipalWithAssert(IPrincipal user);
  234. IAsyncResult IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData);
  235. void IHttpAsyncHandler.EndProcessRequest(IAsyncResult result);
  236. void IHttpHandler.ProcessRequest(HttpContext context);
  237. [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
  238. ISyncContextLock ISyncContext.Enter();
  239. private void ThrowIfEventBindingDisallowed();
  240.  
  241. // Properties
  242. internal EventArgs AppEvent { get; set; }
  243. [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), Browsable(false)]
  244. public HttpApplicationState Application { [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] get; }
  245. private AsyncAppEventHandlersTable AsyncEvents { get; }
  246. internal HttpAsyncResult AsyncResult { get; set; }
  247. [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), Browsable(false)]
  248. public HttpContext Context { get; }
  249. internal string CurrentModuleCollectionKey { get; }
  250. private PipelineModuleStepContainer CurrentModuleContainer { get; }
  251. internal byte[] EntityBuffer { get; }
  252. protected EventHandlerList Events { get; }
  253. internal static List<ModuleConfigurationInfo> IntegratedModuleList { [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] get; }
  254. private bool IsContainerInitalizationAllowed { get; }
  255. internal bool IsRequestCompleted { get; }
  256. internal Exception LastError { get; }
  257. private PipelineModuleStepContainer[] ModuleContainers { get; }
  258. [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
  259. public HttpModuleCollection Modules { [AspNetHostingPermission(SecurityAction.Demand, Level=AspNetHostingPermissionLevel.High)] get; }
  260. [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), Browsable(false)]
  261. public HttpRequest Request { get; }
  262. [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
  263. public HttpResponse Response { get; }
  264. [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), Browsable(false)]
  265. public HttpServerUtility Server { get; }
  266. [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
  267. public HttpSessionState Session { get; }
  268. [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
  269. 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; }
  270. bool IHttpHandler.IsReusable { get; }
  271. bool IRequestCompletedNotifier.IsRequestCompleted { [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] get; }
  272. HttpContext ISyncContext.HttpContext { get; }
  273. [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
  274. public IPrincipal User { get; }
  275.  
  276. // Nested Types
  277. internal class ApplicationStepManager : HttpApplication.StepManager
  278. {
  279. // Fields
  280. private int _currentStepIndex;
  281. private int _endRequestStepIndex;
  282. private HttpApplication.IExecutionStep[] _execSteps;
  283. private int _numStepCalls;
  284. private int _numSyncStepCalls;
  285. private WaitCallback _resumeStepsWaitCallback;
  286.  
  287. // Methods
  288. [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
  289. internal ApplicationStepManager(HttpApplication app);
  290. internal override void BuildSteps(WaitCallback stepCallback);
  291. internal override void InitRequest();
  292. [DebuggerStepperBoundary]
  293. internal override void ResumeSteps(Exception error);
  294. }
  295.  
  296. internal class AsyncAppEventHandler
  297. {
  298. // Fields
  299. private ArrayList _beginHandlers;
  300. private int _count;
  301. private ArrayList _endHandlers;
  302. private ArrayList _stateObjects;
  303.  
  304. // Methods
  305. internal AsyncAppEventHandler();
  306. internal void Add(BeginEventHandler beginHandler, EndEventHandler endHandler, object state);
  307. internal void CreateExecutionSteps(HttpApplication app, ArrayList steps);
  308. internal void Reset();
  309.  
  310. // Properties
  311. internal int Count { [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] get; }
  312. }
  313.  
  314. internal class AsyncAppEventHandlersTable
  315. {
  316. // Fields
  317. private Hashtable _table;
  318.  
  319. // Methods
  320. [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
  321. public AsyncAppEventHandlersTable();
  322. internal void AddHandler(object eventId, BeginEventHandler beginHandler, EndEventHandler endHandler, object state, RequestNotification requestNotification, bool isPost, HttpApplication app);
  323.  
  324. // Properties
  325. internal HttpApplication.AsyncAppEventHandler this[object eventId] { get; }
  326. }
  327.  
  328. internal class AsyncEventExecutionStep : HttpApplication.IExecutionStep
  329. {
  330. // Fields
  331. private HttpApplication _application;
  332. private HttpApplication.AsyncStepCompletionInfo _asyncStepCompletionInfo;
  333. private BeginEventHandler _beginHandler;
  334. private AsyncCallback _completionCallback;
  335. private EndEventHandler _endHandler;
  336. private object _state;
  337. private bool _sync;
  338. private string _targetTypeStr;
  339.  
  340. // Methods
  341. internal AsyncEventExecutionStep(HttpApplication app, BeginEventHandler beginHandler, EndEventHandler endHandler, object state);
  342. internal AsyncEventExecutionStep(HttpApplication app, BeginEventHandler beginHandler, EndEventHandler endHandler, object state, bool useIntegratedPipeline);
  343. private void OnAsyncEventCompletion(IAsyncResult ar);
  344. private void ResumeSteps(Exception error);
  345. [PermissionSet(SecurityAction.Assert, Unrestricted=true)]
  346. private void ResumeStepsWithAssert(Exception error);
  347. void HttpApplication.IExecutionStep.Execute();
  348.  
  349. // Properties
  350. bool HttpApplication.IExecutionStep.CompletedSynchronously { get; }
  351. bool HttpApplication.IExecutionStep.IsCancellable { get; }
  352. }
  353.  
  354. [StructLayout(LayoutKind.Sequential)]
  355. private struct AsyncStepCompletionInfo
  356. {
  357. private volatile int _asyncState;
  358. private ExceptionDispatchInfo _error;
  359. private const int ASYNC_STATE_NONE = ;
  360. private const int ASYNC_STATE_BEGIN_UNWOUND = ;
  361. private const int ASYNC_STATE_CALLBACK_COMPLETED = ;
  362. public bool RegisterAsyncCompletion(Exception error);
  363. public void RegisterBeginUnwound(IAsyncResult asyncResult, out bool operationCompleted, out bool mustCallEndHandler);
  364. public void ReportError();
  365. public void Reset();
  366. }
  367.  
  368. internal class CallFilterExecutionStep : HttpApplication.IExecutionStep
  369. {
  370. // Fields
  371. private HttpApplication _application;
  372.  
  373. // Methods
  374. [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
  375. internal CallFilterExecutionStep(HttpApplication app);
  376. void HttpApplication.IExecutionStep.Execute();
  377.  
  378. // Properties
  379. bool HttpApplication.IExecutionStep.CompletedSynchronously { get; }
  380. bool HttpApplication.IExecutionStep.IsCancellable { get; }
  381. }
  382.  
  383. internal class CallHandlerExecutionStep : HttpApplication.IExecutionStep
  384. {
  385. // Fields
  386. private HttpApplication _application;
  387. private HttpApplication.AsyncStepCompletionInfo _asyncStepCompletionInfo;
  388. private AsyncCallback _completionCallback;
  389. private IHttpAsyncHandler _handler;
  390. private bool _sync;
  391.  
  392. // Methods
  393. internal CallHandlerExecutionStep(HttpApplication app);
  394. private void OnAsyncHandlerCompletion(IAsyncResult ar);
  395. private void ResumeSteps(Exception error);
  396. [PermissionSet(SecurityAction.Assert, Unrestricted=true)]
  397. private void ResumeStepsWithAssert(Exception error);
  398. private static void SuppressPostEndRequestIfNecessary(HttpContext context);
  399. void HttpApplication.IExecutionStep.Execute();
  400.  
  401. // Properties
  402. bool HttpApplication.IExecutionStep.CompletedSynchronously { get; }
  403. bool HttpApplication.IExecutionStep.IsCancellable { get; }
  404. }
  405.  
  406. internal class CancelModuleException
  407. {
  408. // Fields
  409. private bool _timeout;
  410.  
  411. // Methods
  412. [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
  413. internal CancelModuleException(bool timeout);
  414.  
  415. // Properties
  416. internal bool Timeout { [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] get; }
  417. }
  418.  
  419. internal interface IExecutionStep
  420. {
  421. // Methods
  422. void Execute();
  423.  
  424. // Properties
  425. bool CompletedSynchronously { get; }
  426. bool IsCancellable { get; }
  427. }
  428.  
  429. internal class MapHandlerExecutionStep : HttpApplication.IExecutionStep
  430. {
  431. // Fields
  432. private HttpApplication _application;
  433.  
  434. // Methods
  435. [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
  436. internal MapHandlerExecutionStep(HttpApplication app);
  437. void HttpApplication.IExecutionStep.Execute();
  438.  
  439. // Properties
  440. bool HttpApplication.IExecutionStep.CompletedSynchronously { get; }
  441. bool HttpApplication.IExecutionStep.IsCancellable { get; }
  442. }
  443.  
  444. internal class MaterializeHandlerExecutionStep : HttpApplication.IExecutionStep
  445. {
  446. // Fields
  447. private HttpApplication _application;
  448.  
  449. // Methods
  450. [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
  451. internal MaterializeHandlerExecutionStep(HttpApplication app);
  452. void HttpApplication.IExecutionStep.Execute();
  453.  
  454. // Properties
  455. bool HttpApplication.IExecutionStep.CompletedSynchronously { get; }
  456. bool HttpApplication.IExecutionStep.IsCancellable { get; }
  457. }
  458.  
  459. internal class NoopExecutionStep : HttpApplication.IExecutionStep
  460. {
  461. // Methods
  462. [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
  463. internal NoopExecutionStep();
  464. void HttpApplication.IExecutionStep.Execute();
  465.  
  466. // Properties
  467. bool HttpApplication.IExecutionStep.CompletedSynchronously { get; }
  468. bool HttpApplication.IExecutionStep.IsCancellable { get; }
  469. }
  470.  
  471. internal class PipelineStepManager : HttpApplication.StepManager
  472. {
  473. // Fields
  474. private WaitCallback _resumeStepsWaitCallback;
  475. private bool _validateInputCalled;
  476. private bool _validatePathCalled;
  477.  
  478. // Methods
  479. [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
  480. internal PipelineStepManager(HttpApplication app);
  481. internal override void BuildSteps(WaitCallback stepCallback);
  482. internal override void InitRequest();
  483. [DebuggerStepperBoundary]
  484. internal override void ResumeSteps(Exception error);
  485. private Exception ValidateHelper(HttpContext context);
  486. }
  487.  
  488. internal class SendResponseExecutionStep : HttpApplication.IExecutionStep
  489. {
  490. // Fields
  491. private HttpApplication _application;
  492. private EventHandler _handler;
  493. private bool _isHeaders;
  494.  
  495. // Methods
  496. [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
  497. internal SendResponseExecutionStep(HttpApplication app, EventHandler handler, bool isHeaders);
  498. void HttpApplication.IExecutionStep.Execute();
  499.  
  500. // Properties
  501. bool HttpApplication.IExecutionStep.CompletedSynchronously { get; }
  502. bool HttpApplication.IExecutionStep.IsCancellable { get; }
  503. }
  504.  
  505. internal abstract class StepManager
  506. {
  507. // Fields
  508. protected HttpApplication _application;
  509. protected bool _requestCompleted;
  510.  
  511. // Methods
  512. [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
  513. internal StepManager(HttpApplication application);
  514. internal abstract void BuildSteps(WaitCallback stepCallback);
  515. internal void CompleteRequest();
  516. internal abstract void InitRequest();
  517. internal abstract void ResumeSteps(Exception error);
  518.  
  519. // Properties
  520. internal bool IsCompleted { [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] get; }
  521. }
  522.  
  523. internal class SyncEventExecutionStep : HttpApplication.IExecutionStep
  524. {
  525. // Fields
  526. private HttpApplication _application;
  527. private EventHandler _handler;
  528.  
  529. // Methods
  530. [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
  531. internal SyncEventExecutionStep(HttpApplication app, EventHandler handler);
  532. void HttpApplication.IExecutionStep.Execute();
  533.  
  534. // Properties
  535. internal EventHandler Handler { [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] get; }
  536. bool HttpApplication.IExecutionStep.CompletedSynchronously { [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")] get; }
  537. bool HttpApplication.IExecutionStep.IsCancellable { [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")] get; }
  538. }
  539.  
  540. internal class TransitionToWebSocketsExecutionStep : HttpApplication.IExecutionStep
  541. {
  542. // Fields
  543. private readonly HttpApplication _application;
  544.  
  545. // Methods
  546. [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
  547. internal TransitionToWebSocketsExecutionStep(HttpApplication app);
  548. void HttpApplication.IExecutionStep.Execute();
  549.  
  550. // Properties
  551. public bool CompletedSynchronously { [CompilerGenerated, TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] get; [CompilerGenerated] private set; }
  552. public bool IsCancellable { get; }
  553. }
  554.  
  555. internal class UrlMappingsExecutionStep : HttpApplication.IExecutionStep
  556. {
  557. // Fields
  558. private HttpApplication _application;
  559.  
  560. // Methods
  561. [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
  562. internal UrlMappingsExecutionStep(HttpApplication app);
  563. void HttpApplication.IExecutionStep.Execute();
  564.  
  565. // Properties
  566. bool HttpApplication.IExecutionStep.CompletedSynchronously { get; }
  567. bool HttpApplication.IExecutionStep.IsCancellable { get; }
  568. }
  569.  
  570. internal class ValidatePathExecutionStep : HttpApplication.IExecutionStep
  571. {
  572. // Fields
  573. private HttpApplication _application;
  574.  
  575. // Methods
  576. [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
  577. internal ValidatePathExecutionStep(HttpApplication app);
  578. void HttpApplication.IExecutionStep.Execute();
  579.  
  580. // Properties
  581. bool HttpApplication.IExecutionStep.CompletedSynchronously { get; }
  582. bool HttpApplication.IExecutionStep.IsCancellable { get; }
  583. }
  584.  
  585. internal class ValidateRequestExecutionStep : HttpApplication.IExecutionStep
  586. {
  587. // Fields
  588. private HttpApplication _application;
  589.  
  590. // Methods
  591. [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
  592. internal ValidateRequestExecutionStep(HttpApplication app);
  593. void HttpApplication.IExecutionStep.Execute();
  594.  
  595. // Properties
  596. bool HttpApplication.IExecutionStep.CompletedSynchronously { get; }
  597. bool HttpApplication.IExecutionStep.IsCancellable { get; }
  598. }
  599. }
  600.  
  601. Expand Methods
  1. 感兴趣的可以看一下这里面的属性,事件(事件执行顺序并不是写的那个顺序);下面我画张图,简单描述一下过程

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

ASP.NET 运行机制的更多相关文章

  1. ASP.NET运行机制原理

    ASP.NET运行机制原理 一.浏览器和服务器的交互原理 (一).浏览器和服务器交互的简单描述: 1.通俗描述:我们平时通过浏览器来访问网站,其实就相当于你通过浏览器去另一台电脑上访问文件一样,只不过 ...

  2. ASP.NET运行机制原理 ---浏览器与IIS的交互过程 自己学习 网上查了下别人写的总结的很好 就转过来了 和自己写的还好里嘻嘻

    一.浏览器和服务器的交互原理 (一).浏览器和服务器交互的简单描述: 1.通俗描述:我们平时通过浏览器来访问网站,其实就相当于你通过浏览器去访问一台电脑上访问文件一样,只不过浏览器的访问请求是由被访问 ...

  3. WebForm页面生命周期及asp.net运行机制

    1.先上几张原理图着重理解: 现在针对第四副图原理进行解析: 流程: 1.浏览器发送请求 2.服务器软件(IIS)接收,它最终的目的就是为了向客户输出它请求的动态页面生成的html代码. 3.服务器不 ...

  4. 了解认识asp.net运行机制

    asp.net  运行机制 下面了解认识httpModule 要创建一个httpModule类 using System;using System.Collections.Generic;using ...

  5. 我对asp.net运行机制的理解

    有一本书叫<asp.net 本质论>,作者名叫冠军.我看了几次,都没有坚持看下来.这次连续看完了前三章,然后参考网上的资料,总结下我对.net运行机制的理解. 先上两张图: 看着这两张图, ...

  6. ASP.NET 运行机制续(完结)

    上一篇说到applicationInstance会执行一些列的事件.下面是我在msdn上找到有关asp.net程序生命周期相关的描述及图片 声明周期的起始 ASP.NET 应用程序的生命周期以浏览器向 ...

  7. ASP.NET 运行机制详解

    1.浏览器和服务器的交互原理 通俗描述:我们平时通过浏览器来访问网站,其实就相当于你通过浏览器去访问一台电脑上访问文件一样,只不过浏览器的访问请求是由被访问的电脑上的一个 WEB服务器软件来接收处理, ...

  8. 初步了解asp.net运行机制

    客户通过客户端浏览器输入url地址请求资源,服务器接收到客户端请求,首先为http请求分配应用程序池,然后在应用程序池中创建请求需要的管道,这个管道对http请求的各个步骤进行了分配. 当用户第一次请 ...

  9. ASP.NET运行机制之一般处理程序(ashx)

    一. 概述 新建一个ashx文件  代码如下 <%@ WebHandler Language="C#" Class="TestHandler" %> ...

随机推荐

  1. POJ 3259 Wormholes (最短路)

    Wormholes Time Limit: 2000MS   Memory Limit: 65536K Total Submissions: 34302   Accepted: 12520 Descr ...

  2. 干掉拖延症!写给新人的GTD方法

    部门周会上有一个环节是每个同学讲述本周之最:最认可自己的.最反思的.最困惑的.其中,最认可自己,代表自己阶段性的成就感,在从外界取得成就感之前,首先自己要认可自己.最反思,要注意,不能只反不思,要记录 ...

  3. C#导出数据至excel模板

    开源分享最近一个客户要做一个将数据直接输出到指定格式的Excel模板中,略施小计,搞定 其中包含了对Excel的增行和删行,打印预览,表头,表体,表尾的控制 using System; using S ...

  4. HTML插入SWF

    1.插入透明flash代码 <object classid="clsid27CDB6E-AE6D-11cf-96B8-444553540000" codebase=" ...

  5. Android—SDCard数据存取&Environment简介

    1:Environment简介: Environment是android.os包下的一个类,谷歌官方文旦的解释为:Provides access to environment variables(提供 ...

  6. Part 53 to 55 Talking about Reflection in C#

    Part 53 Reflection in C# Part 54 Reflection Example here is the code private void btnDiscover_Click( ...

  7. 我的一点关于把WndProc指向类的成员函数的看法

    转载请注明来源:http://www.cnblogs.com/xuesongshu/ 我以前经常考虑使用WNDCLASS.CreateThread之类的Windows API时如何在类里面调用,传入函 ...

  8. 实例介绍Cocos2d-x精灵菜单和图片菜单

    精灵菜单类是MenuItemSprite,图片菜单类是MenuItemImage.由于MenuItemImage继承于MenuItemSprite,所以图片菜单也属于精灵菜单.为什么叫精灵菜单呢?那是 ...

  9. iOS访问通讯录开发-读取联系人信息

    读取通信录中的联系人一般的过程是先查找联系人记录,然后再访问记录的属性,属性又可以分为单值属性和多值属性.通过下面例子介绍联系人的查询,以及单值属性和多值属性的访问,还有读取联系人中的图片数据. 本案 ...

  10. ReactiveCocoa比较区分replay, replayLast和replayLazily

    一直搞不清楚replayLazily和replay的区别可以直接跳到最后看. 原文:http://spin.atomicobject.com/2014/06/29/replay-replaylast- ...