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

时间:2023-03-08 20:32:23

上一篇说到applicationInstance会执行一些列的事件。下面是我在msdn上找到有关asp.net程序生命周期相关的描述及图片

声明周期的起始

ASP.NET 应用程序的生命周期以浏览器向 Web 服务器(对于 ASP.NET 应用程序,通常为 IIS)发送请求为起点。 ASP.NET 是 Web 服务器下的 ISAPI 扩展。 Web 服务器接收到请求时,会对所请求的文件的文件扩展名进行检查,确定应由哪个 ISAPI 扩展处理该请求,然后将该请求传递给合适的 ISAPI 扩展。 ASP.NET 处理已映射到其上的文件扩展名,如 .aspx、.ascx、.ashx 和 .asmx。

ASP.NET 接收对应用程序的第一个请求

当 ASP.NET 接收到对应用程序中任何资源的第一个请求时,名为 ApplicationManager 的类会创建一个应用程序域。 应用程序域为全局变量提供应用程序隔离,并允许单独卸载每个应用程序。 在应用程序域中,将为名为 HostingEnvironment的类创建一个实例,该实例提供对有关应用程序的信息(如存储该应用程序的文件夹的名称)的访问。

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

为每个请求创建 ASP.NET 核心对象

创建了应用程序域并对 HostingEnvironment 对象进行了实例化之后,ASP.NET 将创建并初始化核心对象,如 HttpContextHttpRequest 和 HttpResponse。 HttpContext 类包含特定于当前应用程序请求的对象,如 HttpRequest 和HttpResponse 对象。 HttpRequest 对象包含有关当前请求的信息,包括 Cookie 和浏览器信息。 HttpResponse 对象包含发送到客户端的响应,包括所有呈现的输出和 Cookie。

将 HttpApplication 对象分配给请求

初始化所有核心应用程序对象之后,将通过创建 HttpApplication 类的实例启动应用程序。 如果应用程序具有 Global.asax 文件,则 ASP.NET 会创建 Global.asax 类(从 HttpApplication 类派生)的一个实例,并使用该派生类表示应用程序。

ASP.NET 运行机制续(完结)注意
第一次在应用程序中请求 ASP.NET 页或进程时,将创建 HttpApplication 的一个新实例。不过,为了尽可能提高性能,可对多个请求重复使用 HttpApplication 实例。

创建 HttpApplication 的实例时,将同时创建所有已配置的模块。 例如,如果将应用程序这样配置,ASP.NET 就会创建一个 SessionStateModule 模块。 创建了所有已配置的模块之后,将调用HttpApplication 类的 Init 方法。

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

由 HttpApplication 管线处理请求。

在处理该请求时将由 HttpApplication 类执行以下事件。 希望扩展 HttpApplication 类的开发人员尤其需要注意这些事件。

  1. 对请求进行验证,将检查浏览器发送的信息,并确定其是否包含潜在恶意标记。 有关更多信息,请参见 ValidateRequest 和脚本侵入概述

  2. 如果已在 Web.config 文件的 UrlMappingsSection 节中配置了任何 URL,则执行 URL 映射。

  3. 引发 BeginRequest 事件;第一个事件

  4. 引发 AuthenticateRequest 事件;验证请求,开始检查用户的身份,一把是获取请求的用户信息

  5. 引发 PostAuthenticateRequest 事件;用户身份已经检查完毕,检查完成后可以通过HttpContext的User属性获取到,微软内置的身份验证机制,平时很少用到

  6. 引发 AuthorizeRequest 事件;开始进行用户权限检查,如果用户没有通过上面的安全检查,一般会直接调至EndRequest事件,也就是直接跳至最后一个事件

  7. 引发 PostAuthorizeRequest 事件;用户请求已经获取授权

  8. 引发 ResolveRequestCache 事件;缓存,如果存在以前处理的缓存结果,则不再进行请求处理工作,返回缓存结果

  9. 引发 PostResolveRequestCache 事件;缓存检查结束

  10. 根据所请求资源的文件扩展名(在应用程序的配置文件中映射),选择实现 IHttpHandler 的类,对请求进行处理。 如果该请求针对从 Page 类派生的对象(页),并且需要对该页进行编译,则 ASP.NET 会在创建该页的实例之前对其进行编译;创建所请求的前台页面类

  11. 引发 PostMapRequestHandler 事件;已经创建处理请求的处理器对象(IHttpHandler)

  12. 引发 AcquireRequestState 事件;获取请求状态,一般用于获取session

  13. 引发 PostAcquireRequestState 事件。已经获取到了session,如果获取到,则将session的值封装到httpcontext中的session属性中去,

  14. 引发 PreRequestHandlerExecute 事件。以为上个事件已经封装了session信息,所以接下来就是验证身份信息的最好位置,如果不通过,直接处理,提高效率。这里也是准备执行处理程序,及调用HttpContext中Handler属性的ProcessRequest

  15. 为该请求调用合适的 IHttpHandler 类的 ProcessRequest 方法(或异步版 IHttpAsyncHandler.BeginProcessRequest)。 例如,如果该请求针对某页,则当前的页实例将处理该请求。

  16. 引发 PostRequestHandlerExecute 事件;页面的ProcessRequest方法执行完成

  17. 引发 ReleaseRequestState 事件;准备释放请求状态session

  18. 引发 PostReleaseRequestState 事件;已经释放请求状态

  19. 如果定义了 Filter 属性,则执行响应筛选。

  20. 引发 UpdateRequestCache 事件;更新缓存

  21. 引发 PostUpdateRequestCache 事件;更新缓存完毕

  22. 引发 EndRequest 事件;结束请求

  23. 引发 PreSendRequestHeaders 事件;可通过发送的头信息设置参数,例如将类型设置为text/plain等

  24. 引发 PreSendRequestContent 事件;处理数据,如配置压缩,则可在这里对数据进行压缩发送

好了,不贴人家的东西了,感兴趣的可以到原网站去看一下。我们重点就是看一下HttpApplication管线处理请求。下面是对事件的解释

  名称 说明
ASP.NET 运行机制续(完结) AcquireRequestState 当 ASP.NET 获取与当前请求关联的当前状态(如会话状态)时发生。
ASP.NET 运行机制续(完结) AuthenticateRequest 当安全模块已建立用户标识时发生。
ASP.NET 运行机制续(完结) AuthorizeRequest 当安全模块已验证用户授权时发生。
ASP.NET 运行机制续(完结) BeginRequest 在 ASP.NET 响应请求时作为 HTTP 执行管线链中的第一个事件发生。
ASP.NET 运行机制续(完结) Disposed 在释放应用程序时发生。
ASP.NET 运行机制续(完结) EndRequest 在 ASP.NET 响应请求时作为 HTTP 执行管线链中的最后一个事件发生。
ASP.NET 运行机制续(完结) Error 当引发未经处理的异常时发生。
ASP.NET 运行机制续(完结) LogRequest 恰好在 ASP.NET 为当前请求执行任何记录之前发生。
ASP.NET 运行机制续(完结) MapRequestHandler 基础结构。在选择了用来响应请求的处理程序时发生。
ASP.NET 运行机制续(完结) PostAcquireRequestState 在已获得与当前请求关联的请求状态(例如会话状态)时发生。
ASP.NET 运行机制续(完结) PostAuthenticateRequest 当安全模块已建立用户标识时发生。
ASP.NET 运行机制续(完结) PostAuthorizeRequest 在当前请求的用户已获授权时发生。
ASP.NET 运行机制续(完结) PostLogRequest 在 ASP.NET 处理完 LogRequest 事件的所有事件处理程序后发生。
ASP.NET 运行机制续(完结) PostMapRequestHandler 在 ASP.NET 已将当前请求映射到相应的事件处理程序时发生。
ASP.NET 运行机制续(完结) PostReleaseRequestState 在 ASP.NET 已完成所有请求事件处理程序的执行并且请求状态数据已存储时发生。
ASP.NET 运行机制续(完结) PostRequestHandlerExecute 在 ASP.NET 事件处理程序(例如,某页或某个 XML Web service)执行完毕时发生。
ASP.NET 运行机制续(完结) PostResolveRequestCache 在 ASP.NET 跳过当前事件处理程序的执行并允许缓存模块满足来自缓存的请求时发生。
ASP.NET 运行机制续(完结) PostUpdateRequestCache 在 ASP.NET 完成缓存模块的更新并存储了用于从缓存中为后续请求提供服务的响应后,发生此事件。
ASP.NET 运行机制续(完结) PreRequestHandlerExecute 恰好在 ASP.NET 开始执行事件处理程序(例如,某页或某个 XML Web services)前发生。
ASP.NET 运行机制续(完结) PreSendRequestContent 恰好在 ASP.NET 向客户端发送内容之前发生。
ASP.NET 运行机制续(完结) PreSendRequestHeaders 恰好在 ASP.NET 向客户端发送 HTTP 标头之前发生。
ASP.NET 运行机制续(完结) ReleaseRequestState 在 ASP.NET 执行完所有请求事件处理程序后发生。 该事件将使状态模块保存当前状态数据。
ASP.NET 运行机制续(完结) RequestCompleted 发生,在与该请求已释放的托管对象。
ASP.NET 运行机制续(完结) ResolveRequestCache 在 ASP.NET 完成授权事件以使缓存模块从缓存中为请求提供服务后发生,从而绕过事件处理程序(例如某个页或 XML Web services)的执行。
ASP.NET 运行机制续(完结) UpdateRequestCache 当 ASP.NET 执行完事件处理程序以使缓存模块存储将用于从缓存为后续请求提供服务的响应时发生。

看一下上面的管线处理请求中标号的10和15,分别是创建前台页面类和调用页面类的ProcessRequest方法的地方。这在我们的上篇文章中说到了。下面我们重点说Application_Start方法执行的地方,ProcessRequest方法都做了什么。

我们都知道Application_Start是程序的入口地方,类似与我们的main函数。但是我在msdn上也没能查到Application_Start是在哪里调用了,但是我们似乎是可以找到这个方法调用的地方,让我们来反编译HttpRuntime(为什么选择反编译这个类?上篇文章里面会有答案)的ProcessRequestNow()方法,继续看_theRuntime.ProcessRequestInternal(wr);我们看ProcessRequestInternal方法中的IHttpHandler applicationInstance = HttpApplicationFactory.GetApplicationInstance(context);,我们可以看出来HttpApplicationFactory是个静态类,我们可以看到该静态类里面有成员internal const string applicationFileName = "global.asax";private static HttpApplicationFactory _theApplicationFactory;private bool _appOnStartCalled;这里我们知道了为什么global.asax文件为什么不能修改文件名,因为这里已经写死了。而后面_appOnStartCalled变量记录着程序的application_start方法是否被调用过,如没被调用过,则为false,进而调用程序的application_start,反之则不进行调用。看GetApplicationInstance中会有判断过程_theApplicationFactory.EnsureAppStartCalled(context);。所以程序的Application_Start()方法的执行顺序肯定先于所有的管线处理请求中的事件。

下面我们来看一下页面的ProcessRequest方法都做了什么操作。也就是开始页面生命周期。

我新建了一个ReflectWeb项目,又添加了demo.aspx页面,页面内容如下

 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Demo.aspx.cs" Inherits="ReflectorWeb.Demo" %>

 <!DOCTYPE html>

 <html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
程序集位置:<%=this.GetType().Assembly.Location %><br />
TextBox1:<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><br />
TextBox2:<input type="text" runat="server" id="TextBox2" /><br />
TextBox3:<input type="text" id="TextBox3" /><br />
</div>
</form>
</body>
</html>

后台类内容很简单

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls; namespace ReflectorWeb
{
public partial class Demo : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Console.WriteLine("test console");
//byte[] tempData = System.Text.Encoding.UTF8.GetBytes("测试Page_Load方法中使用Response.Write方法输出");
Response.Write("测试Page_Load方法中使用Response.Write方法输出");
}
}
}

而页面效果如下

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

下面我们来反编译一下这个程序集,看一下这个程序集里面的内容

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

程序集里面有个demo_aspx类,这就是我们前台页面生成后的类了,页面类代码如下:

 [CompilerGlobalScope]
public class demo_aspx : Demo, IRequiresSessionState, IHttpHandler
{
// Fields
private static object __fileDependencies;
private static bool __initialized;
private static MethodInfo __PageInspector_BeginRenderTracingMethod;
private static MethodInfo __PageInspector_EndRenderTracingMethod;
private static MethodInfo __PageInspector_SetTraceDataMethod; // Methods
static demo_aspx();
[DebuggerNonUserCode]
public demo_aspx();
[DebuggerNonUserCode]
private LiteralControl __BuildControl__control2();
[DebuggerNonUserCode]
private HtmlHead __BuildControl__control3();
[DebuggerNonUserCode]
private HtmlMeta __BuildControl__control4();
[DebuggerNonUserCode]
private HtmlTitle __BuildControl__control5();
[DebuggerNonUserCode]
private LiteralControl __BuildControl__control6();
[DebuggerNonUserCode]
private LiteralControl __BuildControl__control7();
[DebuggerNonUserCode]
private HtmlForm __BuildControlform1();
[DebuggerNonUserCode]
private TextBox __BuildControlTextBox1();
[DebuggerNonUserCode]
private HtmlInputText __BuildControlTextBox2();
[DebuggerNonUserCode]
private void __BuildControlTree(demo_aspx __ctrl);
private void __PageInspector_BeginRenderTracing(object[] parameters);
private void __PageInspector_EndRenderTracing(object[] parameters);
private static MethodInfo __PageInspector_LoadHelper(string helperName);
private void __PageInspector_SetTraceData(object[] parameters);
private void __Renderform1(HtmlTextWriter __w, Control parameterContainer);
[DebuggerNonUserCode]
protected override void FrameworkInitialize();
[DebuggerNonUserCode]
public override int GetTypeHashCode();
[DebuggerNonUserCode]
public override void ProcessRequest(HttpContext context); // Properties
protected HttpApplication ApplicationInstance { get; }
protected DefaultProfile Profile { get; }
} Expand Methods

注意一下,该类继承自Demo类,也就是后台类,而后台类又继承自Page类。下面进入ProcessRequest方法 又调用了父类的ProcessRequest方法base.ProcessRequest(context);这个Page类的一个方法,看这个类的组成

 [Designer("Microsoft.VisualStudio.Web.WebForms.WebFormDesigner, Microsoft.VisualStudio.Web, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", typeof(IRootDesigner)), DefaultEvent("Load"), ToolboxItem(false), DesignerCategory("ASPXCodeBehind"), DesignerSerializer("Microsoft.VisualStudio.Web.WebForms.WebFormCodeDomSerializer, Microsoft.VisualStudio.Web, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.ComponentModel.Design.Serialization.TypeCodeDomSerializer, System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")]
public class Page : TemplateControl, IHttpHandler
{
// Fields
internal HttpApplicationState _application;
private bool _aspCompatMode;
private AspCompatApplicationStep _aspCompatStep;
private bool _asyncMode;
private PageAsyncTaskManager _asyncTaskManager;
private TimeSpan _asyncTimeout;
private bool _asyncTimeoutSet;
private Control _autoPostBackControl;
internal Cache _cache;
private bool _cachedRequestViewState;
private ICallbackEventHandler _callbackControl;
private ArrayList _changedPostDataConsumers;
private string _clientQueryString;
private ClientScriptManager _clientScriptManager;
private string _clientState;
private bool _clientSupportsJavaScript;
private bool _clientSupportsJavaScriptChecked;
private string _clientTarget;
private bool _containsCrossPagePost;
private bool _containsEncryptedViewState;
private IDictionary _contentTemplateCollection;
internal HttpContext _context;
private ArrayList _controlsRequiringPostBack;
private StringSet _controlStateLoadedControlIds;
private Stack _dataBindingContext;
private string _descriptionToBeSet;
private bool _designMode;
private bool _designModeChecked;
private CultureInfo _dynamicCulture;
private CultureInfo _dynamicUICulture;
private ArrayList _enabledControls;
private bool _enableEventValidation;
private bool _enableViewStateMac;
private ViewStateEncryptionMode _encryptionMode;
internal string _errorPage;
private Control _focusedControl;
private string _focusedControlID;
private bool _fOnFormRenderCalled;
private HtmlForm _form;
private bool _fPageLayoutChanged;
private bool _fPostBackScriptRendered;
private bool _fRequirePostBackScript;
private bool _fRequireWebFormsScript;
private bool _fWebFormsScriptRendered;
private bool _haveIdSeparator;
private HtmlHead _header;
internal Dictionary<string, string> _hiddenFieldsToRender;
private char _idSeparator;
private bool _inOnFormRender;
private bool _isCallback;
private bool _isCrossPagePostBack;
private IDictionary _items;
private string _keywordsToBeSet;
private NameValueCollection _leftoverPostData;
private LegacyPageAsyncInfo _legacyAsyncInfo;
private LegacyPageAsyncTaskManager _legacyAsyncTaskManager;
private bool _maintainScrollPosition;
private MasterPage _master;
private VirtualPath _masterPageFile;
private static readonly TimeSpan _maxAsyncTimeout;
private int _maxPageStateFieldLength;
private ModelBindingExecutionContext _modelBindingExecutionContext;
private ModelStateDictionary _modelState;
private bool _needToPersistViewState;
private PageAdapter _pageAdapter;
private SimpleBitVector32 _pageFlags;
private Stack _partialCachingControlStack;
private PageStatePersister _persister;
private RenderMethod _postFormRenderDelegate;
private bool _preInitWorkComplete;
private Page _previousPage;
private VirtualPath _previousPagePath;
private bool _profileTreeBuilt;
internal HybridDictionary _registeredControlsRequiringClearChildControlState;
internal ControlSet _registeredControlsRequiringControlState;
private ArrayList _registeredControlsThatRequirePostBack;
private IPostBackEventHandler _registeredControlThatRequireRaiseEvent;
private string _relativeFilePath;
internal HttpRequest _request;
private NameValueCollection _requestValueCollection;
private string _requestViewState;
private bool _requireFocusScript;
private bool _requireScrollScript;
internal HttpResponse _response;
private static Type _scriptManagerType;
private int _scrollPositionX;
private const string _scrollPositionXID = "__SCROLLPOSITIONX";
private int _scrollPositionY;
private const string _scrollPositionYID = "__SCROLLPOSITIONY";
private HttpSessionState _session;
private bool _sessionRetrieved;
private SmartNavigationSupport _smartNavSupport;
private PageTheme _styleSheet;
private string _styleSheetName;
private int _supportsStyleSheets;
private PageTheme _theme;
private string _themeName;
private string _titleToBeSet;
private int _transactionMode;
private string _uniqueFilePathSuffix;
private UnobtrusiveValidationMode? _unobtrusiveValidationMode;
private NameValueCollection _unvalidatedRequestValueCollection;
private bool _validated;
private string _validatorInvalidControl;
private ValidatorCollection _validators;
private bool _viewStateEncryptionRequested;
private string _viewStateUserKey;
private XhtmlConformanceMode _xhtmlConformanceMode;
private bool _xhtmlConformanceModeSet;
internal const bool BufferDefault = true;
internal const string callbackID = "__CALLBACKID";
internal const string callbackIndexID = "__CALLBACKINDEX";
internal const string callbackLoadScriptID = "__CALLBACKLOADSCRIPT";
internal const string callbackParameterID = "__CALLBACKPARAM";
internal static readonly int DefaultAsyncTimeoutSeconds;
internal static readonly int DefaultMaxPageStateFieldLength;
private const string EnabledControlArray = "__enabledControlArray";
internal const bool EnableEventValidationDefault = true;
internal const bool EnableViewStateMacDefault = true;
internal const ViewStateEncryptionMode EncryptionModeDefault = ViewStateEncryptionMode.Auto;
internal static readonly object EventInitComplete;
internal static readonly object EventLoadComplete;
internal static readonly object EventPreInit;
internal static readonly object EventPreLoad;
internal static readonly object EventPreRenderComplete;
internal static readonly object EventSaveStateComplete;
internal const string EventValidationPrefixID = "__EVENTVALIDATION";
private static readonly Version FocusMinimumEcmaVersion;
private static readonly Version FocusMinimumJScriptVersion;
private const string HiddenClassName = "aspNetHidden";
private const int isCrossPagePostRequest = ;
private const int isExportingWebPart = ;
private const int isExportingWebPartShared = ;
private const int isPartialRenderingSupported = 0x10;
private const int isPartialRenderingSupportedSet = 0x20;
private static readonly Version JavascriptMinimumVersion;
private const string lastFocusID = "__LASTFOCUS";
internal const bool MaintainScrollPositionOnPostBackDefault = false;
private static readonly Version MSDomScrollMinimumVersion;
private const string PageID = "__Page";
private const string PageReEnableControlsScriptKey = "PageReEnableControlsScript";
private const string PageRegisteredControlsThatRequirePostBackKey = "__ControlsRequirePostBackKey__";
private const string PageScrollPositionScriptKey = "PageScrollPositionScript";
private const string PageSubmitScriptKey = "PageSubmitScript";
[EditorBrowsable(EditorBrowsableState.Never)]
public const string postEventArgumentID = "__EVENTARGUMENT";
[EditorBrowsable(EditorBrowsableState.Never)]
public const string postEventSourceID = "__EVENTTARGET";
internal const string previousPageID = "__PREVIOUSPAGE";
private static StringSet s_systemPostFields;
private static char[] s_varySeparator;
private const int skipFormActionValidation = 0x40;
internal const bool SmartNavigationDefault = false;
private const int styleSheetInitialized = ;
internal const string systemPostFieldPrefix = "__";
private static readonly string UniqueFilePathSuffixID;
internal const string ViewStateEncryptionID = "__VIEWSTATEENCRYPTED";
internal const string ViewStateFieldCountID = "__VIEWSTATEFIELDCOUNT";
internal const string ViewStateFieldPrefixID = "__VIEWSTATE";
internal const string WebPartExportID = "__WEBPARTEXPORT"; // Events
[EditorBrowsable(EditorBrowsableState.Advanced)]
public event EventHandler InitComplete;
[EditorBrowsable(EditorBrowsableState.Advanced)]
public event EventHandler LoadComplete;
public event EventHandler PreInit;
[EditorBrowsable(EditorBrowsableState.Advanced)]
public event EventHandler PreLoad;
[EditorBrowsable(EditorBrowsableState.Advanced)]
public event EventHandler PreRenderComplete;
[EditorBrowsable(EditorBrowsableState.Advanced)]
public event EventHandler SaveStateComplete; // Methods
static Page();
public Page();
[EditorBrowsable(EditorBrowsableState.Never)]
protected internal void AddContentTemplate(string templateName, ITemplate template);
[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
public void AddOnPreRenderCompleteAsync(BeginEventHandler beginHandler, EndEventHandler endHandler);
public void AddOnPreRenderCompleteAsync(BeginEventHandler beginHandler, EndEventHandler endHandler, object state);
[EditorBrowsable(EditorBrowsableState.Never)]
protected internal void AddWrappedFileDependencies(object virtualFileDependencies);
internal void ApplyControlSkin(Control ctrl);
[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
internal bool ApplyControlStyleSheet(Control ctrl);
private void ApplyMasterPage();
[EditorBrowsable(EditorBrowsableState.Never)]
protected IAsyncResult AspCompatBeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData);
[EditorBrowsable(EditorBrowsableState.Never)]
protected void AspCompatEndProcessRequest(IAsyncResult result);
[EditorBrowsable(EditorBrowsableState.Never)]
protected IAsyncResult AsyncPageBeginProcessRequest(HttpContext context, AsyncCallback callback, object extraData);
[EditorBrowsable(EditorBrowsableState.Never)]
protected void AsyncPageEndProcessRequest(IAsyncResult result);
private void AsyncPageProcessRequestBeforeAsyncPointCancellableCallback(object state);
internal void BeginFormRender(HtmlTextWriter writer, string formUniqueID);
private void BuildPageProfileTree(bool enableViewState);
private void CheckRemainingAsyncTasks(bool isThreadAbort);
private CancellationTokenSource CreateCancellationTokenFromAsyncTimeout();
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected internal virtual HtmlTextWriter CreateHtmlTextWriter(TextWriter tw);
public static HtmlTextWriter CreateHtmlTextWriterFromType(TextWriter tw, Type writerType);
internal static HtmlTextWriter CreateHtmlTextWriterInternal(TextWriter tw, HttpRequest request);
internal IStateFormatter2 CreateStateFormatter();
private CultureInfo CultureFromUserLanguages(bool specific);
internal ICollection DecomposeViewStateIntoChunks();
internal static string DecryptString(string s, Purpose purpose);
[EditorBrowsable(EditorBrowsableState.Never)]
public void DesignerInitialize();
private bool DetermineIsExportingWebPart();
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected internal virtual NameValueCollection DeterminePostBackMode();
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected internal virtual NameValueCollection DeterminePostBackModeUnvalidated();
internal static string EncryptString(string s, Purpose purpose);
internal void EndFormRender(HtmlTextWriter writer, string formUniqueID);
internal void EndFormRenderArrayAndExpandoAttribute(HtmlTextWriter writer, string formUniqueID);
internal void EndFormRenderHiddenFields(HtmlTextWriter writer, string formUniqueID);
internal void EndFormRenderPostBackAndWebFormsScript(HtmlTextWriter writer, string formUniqueID);
public void ExecuteRegisteredAsyncTasks();
private void ExportWebPart(string exportedWebPartID);
public override Control FindControl(string id);
protected override void FrameworkInitialize();
internal NameValueCollection GetCollectionBasedOnMethod(bool dontReturnNull);
public object GetDataItem();
internal bool GetDesignModeInternal();
[Obsolete("The recommended alternative is ClientScript.GetPostBackEventReference. http://go.microsoft.com/fwlink/?linkid=14202"), EditorBrowsable(EditorBrowsableState.Advanced)]
public string GetPostBackClientEvent(Control control, string argument);
[EditorBrowsable(EditorBrowsableState.Advanced), Obsolete("The recommended alternative is ClientScript.GetPostBackClientHyperlink. http://go.microsoft.com/fwlink/?linkid=14202")]
public string GetPostBackClientHyperlink(Control control, string argument);
[Obsolete("The recommended alternative is ClientScript.GetPostBackEventReference. http://go.microsoft.com/fwlink/?linkid=14202"), EditorBrowsable(EditorBrowsableState.Advanced)]
public string GetPostBackEventReference(Control control);
[Obsolete("The recommended alternative is ClientScript.GetPostBackEventReference. http://go.microsoft.com/fwlink/?linkid=14202"), EditorBrowsable(EditorBrowsableState.Advanced)]
public string GetPostBackEventReference(Control control, string argument);
[EditorBrowsable(EditorBrowsableState.Never)]
public virtual int GetTypeHashCode();
internal override string GetUniqueIDPrefix();
public ValidatorCollection GetValidators(string validationGroup);
internal WithinCancellableCallbackTaskAwaitable GetWaitForPreviousStepCompletionAwaitable();
[EditorBrowsable(EditorBrowsableState.Never)]
protected object GetWrappedFileDependencies(string[] virtualFileDependencies);
private bool HandleError(Exception e);
protected virtual void InitializeCulture();
internal void InitializeStyleSheet();
private void InitializeThemes();
private void InitializeWriter(HtmlTextWriter writer);
[EditorBrowsable(EditorBrowsableState.Never)]
protected internal virtual void InitOutputCache(OutputCacheParameters cacheSettings);
[EditorBrowsable(EditorBrowsableState.Never), TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
protected virtual void InitOutputCache(int duration, string varyByHeader, string varyByCustom, OutputCacheLocation location, string varyByParam);
[EditorBrowsable(EditorBrowsableState.Never)]
protected virtual void InitOutputCache(int duration, string varyByContentEncoding, string varyByHeader, string varyByCustom, OutputCacheLocation location, string varyByParam);
[Obsolete("The recommended alternative is ClientScript.IsClientScriptBlockRegistered(string key). http://go.microsoft.com/fwlink/?linkid=14202")]
public bool IsClientScriptBlockRegistered(string key);
[Obsolete("The recommended alternative is ClientScript.IsStartupScriptRegistered(string key). http://go.microsoft.com/fwlink/?linkid=14202")]
public bool IsStartupScriptRegistered(string key);
internal static bool IsSystemPostField(string field);
private IAsyncResult LegacyAsyncPageBeginProcessRequest(HttpContext context, AsyncCallback callback, object extraData);
private void LegacyAsyncPageEndProcessRequest(IAsyncResult result);
private void LoadAllState();
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected internal virtual object LoadPageStateFromPersistenceMedium();
internal void LoadScrollPosition();
public string MapPath(string virtualPath);
internal void OnFormPostRender(HtmlTextWriter writer);
internal void OnFormRender();
protected internal override void OnInit(EventArgs e);
protected virtual void OnInitComplete(EventArgs e);
protected virtual void OnLoadComplete(EventArgs e);
protected virtual void OnPreInit(EventArgs e);
protected virtual void OnPreLoad(EventArgs e);
protected virtual void OnPreRenderComplete(EventArgs e);
protected virtual void OnSaveStateComplete(EventArgs e);
private void PerformPreInit();
[DebuggerStepThrough, AsyncStateMachine(typeof(<PerformPreInitAsync>d__c))]
private Task PerformPreInitAsync();
private void PerformPreRenderComplete();
internal void PopCachingControl();
internal void PopDataBindingContext();
private void PrepareCallback(string callbackControlID);
[AsyncStateMachine(typeof(<PrepareCallbackAsync>d__1f)), DebuggerStepThrough]
private Task PrepareCallbackAsync(string callbackControlID);
private void ProcessPostData(NameValueCollection postData, bool fBeforeLoad);
private void ProcessRequest();
[EditorBrowsable(EditorBrowsableState.Never)]
public virtual void ProcessRequest(HttpContext context);
private void ProcessRequest(bool includeStagesBeforeAsyncPoint, bool includeStagesAfterAsyncPoint);
[AsyncStateMachine(typeof(<ProcessRequestAsync>d__2c)), DebuggerStepThrough]
private Task ProcessRequestAsync(HttpContext context);
[DebuggerStepThrough, AsyncStateMachine(typeof(<ProcessRequestAsync>d__10))]
private Task ProcessRequestAsync(bool includeStagesBeforeAsyncPoint, bool includeStagesAfterAsyncPoint);
private void ProcessRequestCleanup();
private void ProcessRequestEndTrace();
private void ProcessRequestMain();
private void ProcessRequestMain(bool includeStagesBeforeAsyncPoint, bool includeStagesAfterAsyncPoint);
[DebuggerStepThrough, AsyncStateMachine(typeof(<ProcessRequestMainAsync>d__14))]
private Task ProcessRequestMainAsync(bool includeStagesBeforeAsyncPoint, bool includeStagesAfterAsyncPoint);
private void ProcessRequestTransacted();
[PermissionSet(SecurityAction.Assert, Unrestricted=true)]
private void ProcessRequestWithAssert(HttpContext context);
private void ProcessRequestWithNoAssert(HttpContext context);
internal void PushCachingControl(BasePartialCachingControl c);
internal void PushDataBindingContext(object dataItem);
internal void RaiseChangedEvents();
[DebuggerStepThrough, AsyncStateMachine(typeof(<RaiseChangedEventsAsync>d__5))]
internal Task RaiseChangedEventsAsync();
private void RaisePostBackEvent(NameValueCollection postData);
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual void RaisePostBackEvent(IPostBackEventHandler sourceControl, string eventArgument);
[Obsolete("The recommended alternative is ClientScript.RegisterArrayDeclaration(string arrayName, string arrayValue). http://go.microsoft.com/fwlink/?linkid=14202"), EditorBrowsable(EditorBrowsableState.Advanced)]
public void RegisterArrayDeclaration(string arrayName, string arrayValue);
public void RegisterAsyncTask(PageAsyncTask task);
[Obsolete("The recommended alternative is ClientScript.RegisterClientScriptBlock(Type type, string key, string script). http://go.microsoft.com/fwlink/?linkid=14202"), EditorBrowsable(EditorBrowsableState.Advanced)]
public virtual void RegisterClientScriptBlock(string key, string script);
internal void RegisterEnabledControl(Control control);
internal void RegisterFocusScript();
[EditorBrowsable(EditorBrowsableState.Advanced), Obsolete("The recommended alternative is ClientScript.RegisterHiddenField(string hiddenFieldName, string hiddenFieldInitialValue). http://go.microsoft.com/fwlink/?linkid=14202")]
public virtual void RegisterHiddenField(string hiddenFieldName, string hiddenFieldInitialValue);
[Obsolete("The recommended alternative is ClientScript.RegisterOnSubmitStatement(Type type, string key, string script). http://go.microsoft.com/fwlink/?linkid=14202"), EditorBrowsable(EditorBrowsableState.Advanced)]
public void RegisterOnSubmitStatement(string key, string script);
internal void RegisterPostBackScript();
internal void RegisterRequiresClearChildControlState(Control control);
[EditorBrowsable(EditorBrowsableState.Advanced)]
public void RegisterRequiresControlState(Control control);
[EditorBrowsable(EditorBrowsableState.Advanced)]
public void RegisterRequiresPostBack(Control control);
[EditorBrowsable(EditorBrowsableState.Advanced)]
public virtual void RegisterRequiresRaiseEvent(IPostBackEventHandler control);
public void RegisterRequiresViewStateEncryption();
[EditorBrowsable(EditorBrowsableState.Advanced), Obsolete("The recommended alternative is ClientScript.RegisterStartupScript(Type type, string key, string script). http://go.microsoft.com/fwlink/?linkid=14202")]
public virtual void RegisterStartupScript(string key, string script);
[EditorBrowsable(EditorBrowsableState.Advanced)]
public void RegisterViewStateHandler();
internal void RegisterWebFormsScript();
protected internal override void Render(HtmlTextWriter writer);
private void RenderCallback();
private bool RenderDivAroundHiddenInputs(HtmlTextWriter writer);
private void RenderPostBackScript(HtmlTextWriter writer, string formUniqueID);
internal void RenderViewStateFields(HtmlTextWriter writer);
private void RenderWebFormsScript(HtmlTextWriter writer);
public bool RequiresControlState(Control control);
internal void ResetOnFormRenderCalled();
private void RestoreCultures(Thread currentThread, CultureInfo prevCulture, CultureInfo prevUICulture);
private void SaveAllState();
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected internal virtual void SavePageStateToPersistenceMedium(object state);
internal void SetActiveValueProvider(IValueProvider valueProvider);
private void SetCulture(Thread currentThread, CultureInfo currentCulture, CultureInfo currentUICulture);
[SecurityPermission(SecurityAction.Assert, ControlThread=true)]
private void SetCultureWithAssert(Thread currentThread, CultureInfo currentCulture, CultureInfo currentUICulture);
public void SetFocus(string clientID);
public void SetFocus(Control control);
internal void SetForm(HtmlForm form);
internal void SetHeader(HtmlHead header);
private void SetIntrinsics(HttpContext context);
private void SetIntrinsics(HttpContext context, bool allowAsync);
internal void SetPostFormRenderDelegate(RenderMethod renderMethod);
internal void SetPreviousPage(Page previousPage);
internal void SetValidatorInvalidControlFocus(string clientID);
internal bool ShouldLoadControlState(Control control);
[SecurityPermission(SecurityAction.Assert, ControlThread=true)]
internal static void ThreadResetAbortWithAssert();
public virtual bool TryUpdateModel<TModel>(TModel model) where TModel: class;
public virtual bool TryUpdateModel<TModel>(TModel model, IValueProvider valueProvider) where TModel: class;
internal override void UnloadRecursive(bool dispose);
[EditorBrowsable(EditorBrowsableState.Advanced)]
public void UnregisterRequiresControlState(Control control);
public virtual void UpdateModel<TModel>(TModel model) where TModel: class;
public virtual void UpdateModel<TModel>(TModel model, IValueProvider valueProvider) where TModel: class;
public virtual void Validate();
public virtual void Validate(string validationGroup);
private void ValidateRawUrlIfRequired();
[EditorBrowsable(EditorBrowsableState.Advanced)]
public virtual void VerifyRenderingInServerForm(Control control); // Properties
private IValueProvider ActiveValueProvider { [CompilerGenerated, TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] get; [CompilerGenerated] set; }
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public HttpApplicationState Application { [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] get; }
[EditorBrowsable(EditorBrowsableState.Never)]
protected bool AspCompatMode { [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; }
[EditorBrowsable(EditorBrowsableState.Never)]
protected bool AsyncMode { [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; }
[Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public TimeSpan AsyncTimeout { get; set; }
public Control AutoPostBackControl { [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; }
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public bool Buffer { get; set; }
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), Browsable(false)]
public Cache Cache { get; }
internal string ClientOnSubmitEvent { get; }
public string ClientQueryString { get; }
public ClientScriptManager ClientScript { get; }
internal string ClientState { [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; }
internal bool ClientSupportsFocus { get; }
internal bool ClientSupportsJavaScript { get; }
[WebSysDescription("Page_ClientTarget"), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), DefaultValue(""), Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced)]
public string ClientTarget { get; set; }
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public int CodePage { get; set; }
internal bool ContainsCrossPagePost { [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; }
internal bool ContainsEncryptedViewState { [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; }
internal bool ContainsTheme { get; }
[EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), Browsable(false)]
public string ContentType { get; set; }
protected internal override HttpContext Context { [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")] get; }
private StringSet ControlStateLoadedControlIds { get; }
[Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public string Culture { get; set; }
internal CultureInfo DynamicCulture { [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] get; }
internal CultureInfo DynamicUICulture { [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] get; }
private ArrayList EnabledControls { get; }
[DefaultValue(true), Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), EditorBrowsable(EditorBrowsableState.Never)]
public virtual bool EnableEventValidation { [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] get; set; }
[Browsable(false)]
public override bool EnableViewState { get; set; }
[EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), Browsable(false)]
public bool EnableViewStateMac { [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] get; set; }
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), Browsable(false), WebSysDescription("Page_ErrorPage"), DefaultValue("")]
public string ErrorPage { [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; }
[Obsolete("The recommended alternative is HttpResponse.AddFileDependencies. http://go.microsoft.com/fwlink/?linkid=14202"), EditorBrowsable(EditorBrowsableState.Never)]
protected ArrayList FileDependencies { set; }
internal Control FocusedControl { [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] get; }
internal string FocusedControlID { get; }
public HtmlForm Form { [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] get; }
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public HtmlHead Header { [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] get; }
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public override string ID { get; set; }
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public virtual char IdSeparator { get; }
public bool IsAsync { [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] get; }
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), Browsable(false)]
public bool IsCallback { [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] get; }
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool IsCrossPagePostBack { [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] get; }
internal bool IsExportingWebPart { get; }
internal bool IsExportingWebPartShared { get; }
internal bool IsInAspCompatMode { [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] get; }
internal bool IsInOnFormRender { [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] get; }
internal bool IsPartialRenderingSupported { get; }
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool IsPostBack { get; }
public bool IsPostBackEventControlRegistered { get; }
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public bool IsReusable { get; }
internal bool IsTransacted { get; }
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool IsValid { get; }
[Browsable(false)]
public IDictionary Items { get; }
internal string LastFocusedControl { [AspNetHostingPermission(SecurityAction.Assert, Level=AspNetHostingPermissionLevel.Low)] get; }
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public int LCID { get; set; }
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), Browsable(false)]
public bool MaintainScrollPositionOnPostBack { get; set; }
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), WebSysDescription("MasterPage_MasterPage"), Browsable(false)]
public MasterPage Master { get; }
[WebSysDescription("MasterPage_MasterPageFile"), DefaultValue(""), WebCategory("Behavior")]
public virtual string MasterPageFile { get; set; }
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
public int MaxPageStateFieldLength { [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] get; set; }
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), Bindable(true), Localizable(true)]
public string MetaDescription { get; set; }
[Localizable(true), Bindable(true), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public string MetaKeywords { get; set; }
public ModelBindingExecutionContext ModelBindingExecutionContext { get; }
public ModelStateDictionary ModelState { get; }
public PageAdapter PageAdapter { get; }
protected virtual PageStatePersister PageStatePersister { get; }
internal Stack PartialCachingControlStack { [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] get; }
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), Browsable(false)]
public Page PreviousPage { get; }
internal string RelativeFilePath { get; }
private bool RenderDisabledControlsScript { get; }
internal bool RenderFocusScript { [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] get; }
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), Browsable(false)]
public HttpRequest Request { [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")] get; }
internal HttpRequest RequestInternal { [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] get; }
internal NameValueCollection RequestValueCollection { [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] get; }
internal string RequestViewStateString { get; }
internal bool RequiresViewStateEncryptionInternal { get; }
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public HttpResponse Response { get; }
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public string ResponseEncoding { get; set; }
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public RouteData RouteData { get; }
internal IScriptManager ScriptManager { get; }
internal Type ScriptManagerType { get; set; }
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), Browsable(false)]
public HttpServerUtility Server { get; }
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public virtual HttpSessionState Session { get; }
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), DefaultValue(false)]
public bool SkipFormActionValidation { get; set; }
[Filterable(false), Browsable(false), Obsolete("The recommended alternative is Page.SetFocus and Page.MaintainScrollPositionOnPostBack. http://go.microsoft.com/fwlink/?linkid=14202")]
public bool SmartNavigation { get; set; }
[Filterable(false), Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public virtual string StyleSheetTheme { [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] get; set; }
internal bool SupportsStyleSheets { get; }
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), Browsable(false)]
public virtual string Theme { [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] get; set; }
[Bindable(true), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), Localizable(true)]
public string Title { get; set; }
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public TraceContext Trace { get; }
[EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), Browsable(false)]
public bool TraceEnabled { get; set; }
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), EditorBrowsable(EditorBrowsableState.Never)]
public TraceMode TraceModeValue { get; set; }
[EditorBrowsable(EditorBrowsableState.Never)]
protected int TransactionMode { [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; }
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), EditorBrowsable(EditorBrowsableState.Advanced), Browsable(false)]
public string UICulture { get; set; }
protected internal virtual string UniqueFilePathSuffix { get; }
[WebSysDescription("Page_UnobtrusiveValidationMode"), DefaultValue(), WebCategory("Behavior")]
public UnobtrusiveValidationMode UnobtrusiveValidationMode { get; set; }
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), Browsable(false)]
public IPrincipal User { get; }
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false), DefaultValue()]
public override ValidateRequestMode ValidateRequestMode { get; set; }
internal string ValidatorInvalidControl { get; }
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public ValidatorCollection Validators { get; }
[Browsable(false), DefaultValue(), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), EditorBrowsable(EditorBrowsableState.Never)]
public ViewStateEncryptionMode ViewStateEncryptionMode { [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] get; set; }
[Browsable(false)]
public string ViewStateUserKey { [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] get; set; }
[Browsable(false)]
public override bool Visible { [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")] get; set; }
internal XhtmlConformanceMode XhtmlConformanceMode { get; } // Nested Types
[CompilerGenerated]
private struct <PerformPreInitAsync>d__c : IAsyncStateMachine
{
// Fields
public int <>1__state;
public Page <>4__this;
public IDisposable <>7__wrapd;
public AsyncTaskMethodBuilder <>t__builder;
private object <>t__stack;
private WithinCancellableCallbackTaskAwaitable.WithinCancellableCallbackTaskAwaiter <>u__$awaitere; // Methods
private void MoveNext();
[DebuggerHidden]
private void SetStateMachine(IAsyncStateMachine param0);
} [CompilerGenerated]
private struct <PrepareCallbackAsync>d__1f : IAsyncStateMachine
{
// Fields
public int <>1__state;
public Page <>4__this;
public IDisposable <>7__wrap21;
public AsyncTaskMethodBuilder <>t__builder;
private object <>t__stack;
private WithinCancellableCallbackTaskAwaitable.WithinCancellableCallbackTaskAwaiter <>u__$awaiter22;
public string <param>5__20;
public string callbackControlID; // Methods
private void MoveNext();
[DebuggerHidden]
private void SetStateMachine(IAsyncStateMachine param0);
} [CompilerGenerated]
private struct <ProcessRequestAsync>d__10 : IAsyncStateMachine
{
// Fields
public int <>1__state;
public Page <>4__this;
public AsyncTaskMethodBuilder <>t__builder;
private object <>t__stack;
private WithinCancellableCallbackTaskAwaitable.WithinCancellableCallbackTaskAwaiter <>u__$awaiter12;
public bool <needToCallEndTrace>5__11;
public bool includeStagesAfterAsyncPoint;
public bool includeStagesBeforeAsyncPoint; // Methods
private void MoveNext();
[DebuggerHidden]
private void SetStateMachine(IAsyncStateMachine param0);
} [CompilerGenerated]
private struct <ProcessRequestAsync>d__2c : IAsyncStateMachine
{
// Fields
public int <>1__state;
public Page <>4__this;
public AsyncTaskMethodBuilder <>t__builder;
private object <>t__stack;
private TaskAwaiter <>u__$awaiter2f;
public CancellationToken <cancellationToken>5__2e;
public CancellationTokenSource <cancellationTokenSource>5__2d;
public HttpContext context;
public Page.<>c__DisplayClass2a CS$<>8__locals2b; // Methods
private void MoveNext();
[DebuggerHidden]
private void SetStateMachine(IAsyncStateMachine param0);
} [CompilerGenerated]
private struct <ProcessRequestMainAsync>d__14 : IAsyncStateMachine
{
// Fields
public int <>1__state;
public Page <>4__this;
public IDisposable <>7__wrap1a;
public IDisposable <>7__wrap1b;
public IDisposable <>7__wrap1c;
public IDisposable <>7__wrap1d;
public AsyncTaskMethodBuilder <>t__builder;
private object <>t__stack;
private WithinCancellableCallbackTaskAwaitable.WithinCancellableCallbackTaskAwaiter <>u__$awaiter19;
public string <callbackControlId>5__17;
public HttpContext <con>5__15;
public string <exportedWebPartID>5__16;
public Task <initRecursiveTask>5__18;
public bool includeStagesAfterAsyncPoint;
public bool includeStagesBeforeAsyncPoint; // Methods
private void MoveNext();
[DebuggerHidden]
private void SetStateMachine(IAsyncStateMachine param0);
} [CompilerGenerated]
private struct <RaiseChangedEventsAsync>d__5 : IAsyncStateMachine
{
// Fields
public int <>1__state;
public Page <>4__this;
public IDisposable <>7__wrap9;
public AsyncTaskMethodBuilder <>t__builder;
private object <>t__stack;
private WithinCancellableCallbackTaskAwaitable.WithinCancellableCallbackTaskAwaiter <>u__$awaitera;
public Control <c>5__7;
public IPostBackDataHandler <changedPostDataConsumer>5__8;
public int <i>5__6; // Methods
private void MoveNext();
[DebuggerHidden]
private void SetStateMachine(IAsyncStateMachine param0);
} private class LegacyPageAsyncInfo
{
// Fields
private HttpApplication _app;
private bool _asyncPointReached;
private HttpAsyncResult _asyncResult;
private ArrayList _beginHandlers;
private bool _callerIsBlocking;
private WaitCallback _callHandlersThreadpoolCallback;
private bool _completed;
private AsyncCallback _completionCallback;
private int _currentHandler;
private ArrayList _endHandlers;
private Exception _error;
private int _handlerCount;
private Page _page;
private ArrayList _stateObjects;
private AspNetSynchronizationContextBase _syncContext; // Methods
internal LegacyPageAsyncInfo(Page page);
internal void AddHandler(BeginEventHandler beginHandler, EndEventHandler endHandler, object state);
internal void CallHandlers(bool onPageThread);
private void CallHandlersFromThreadpoolThread(object data);
private void CallHandlersPossiblyUnderLock(bool onPageThread);
private void OnAsyncHandlerCompletion(IAsyncResult ar);
internal void SetError(Exception error); // Properties
internal bool AsyncPointReached { get; set; }
internal HttpAsyncResult AsyncResult { get; set; }
internal bool CallerIsBlocking { get; set; }
}
} Expand Methods

内容好多啊,这也就是为什么我们在后台类中可以访问Response,Request,Server等属性的原因了。看下这个类的ProcessRequest

 [EditorBrowsable(EditorBrowsableState.Never)]
public virtual void ProcessRequest(HttpContext context)
{
if ((HttpRuntime.NamedPermissionSet != null) && !HttpRuntime.DisableProcessRequestInApplicationTrust)
{
if (!HttpRuntime.ProcessRequestInApplicationTrust)
{
this.ProcessRequestWithAssert(context);
return;
}
if (base.NoCompile)
{
HttpRuntime.NamedPermissionSet.PermitOnly();
}
}
this.ProcessRequestWithNoAssert(context);
}

进入---》this.ProcessRequestWithAssert(context);---》this.ProcessRequestWithNoAssert(context);---》this.ProcessRequest();---》this.ProcessRequest(true, true);仔细看下最后这个方法this.ProcessRequest(true, true);

 private void ProcessRequest(bool includeStagesBeforeAsyncPoint, bool includeStagesAfterAsyncPoint)
{
if (includeStagesBeforeAsyncPoint)
{
this.FrameworkInitialize();
base.ControlState = ControlState.FrameworkInitialized;
}
bool flag = this.Context.WorkerRequest is IIS7WorkerRequest;
try
{
try
{
if (this.IsTransacted)
{
this.ProcessRequestTransacted();
}
else
{
this.ProcessRequestMain(includeStagesBeforeAsyncPoint, includeStagesAfterAsyncPoint);
}
if (includeStagesAfterAsyncPoint)
{
flag = false;
this.ProcessRequestEndTrace();
}
}
catch (ThreadAbortException)
{
try
{
if (flag)
{
this.ProcessRequestEndTrace();
}
}
catch
{
}
}
finally
{
if (includeStagesAfterAsyncPoint)
{
this.ProcessRequestCleanup();
}
}
}
catch
{
throw;
}
}
注意一下this.FrameworkInitialize();这个FramworkInitiallize在Page类中是虚方法,而在页面类中重写了这个方法,其实通过this调用,也说明了这里这个方法是调用前台页面类的方法。看下前台页面类的FramworkInitialize方法。
 [DebuggerNonUserCode]
protected override void FrameworkInitialize()
{
base.FrameworkInitialize();
this.__BuildControlTree(this);
base.AddWrappedFileDependencies(__fileDependencies);
base.Request.ValidateInput();
}

先调用了父类的FrameworkInitialize方法,我们主要看这句调用this.__BuildControlTree(this);从表面上我们可以看出是构建控件树,参数this,也就是将当前页面类对象当做参数传进去,我们进入到这个方法内部查看

 [DebuggerNonUserCode]
private void __BuildControlTree(demo_aspx __ctrl)
{
this.InitializeCulture();
LiteralControl __ctrl1 = this.__BuildControl__control2();
IParserAccessor __parser = __ctrl;
__parser.AddParsedSubObject(__ctrl1);
HtmlHead __ctrl2 = this.__BuildControl__control3();
__parser.AddParsedSubObject(__ctrl2);
LiteralControl __ctrl3 = this.__BuildControl__control6();
__parser.AddParsedSubObject(__ctrl3);
HtmlForm __ctrl4 = this.__BuildControlform1();
__parser.AddParsedSubObject(__ctrl4);
LiteralControl __ctrl5 = this.__BuildControl__control7();
__parser.AddParsedSubObject(__ctrl5);
}

注意,这里生成的内容是根据前台页面服务器端控件生成的,也就是说前台页面中包含的内容不同,这里生成的代码也会不同。控件越多,代码也会越多。我们只分析一部分,其实后面都是一样的原理。

LiteralControl __ctrl1 = this.__BuildControl__control2();我们看这句,查看一下this.__BuildControl__control2();注意,这是前台类中的一个方法
 [DebuggerNonUserCode]
private LiteralControl __BuildControl__control2()
{
LiteralControl __ctrl = new LiteralControl("\r\n\r\n<!DOCTYPE html>\r\n\r\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\r\n");
object[] CS$$ = new object[];
CS$$[] = __ctrl;
CS$$[] = 0x67;
CS$$[] = 0x44;
CS$$[] = true;
this.__PageInspector_SetTraceData(CS$$);
return __ctrl;
}
可以与前台页面的html代码对照一下

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

LiteralControl这个控件类就是封装字符串的,在asp.net看来,只要不是c#代码及服务端控件,都是字符串。例如后面的<input type="text" id="TextBox3" />

将这个控件对象(_ctrl)返回。继续看下一句,IParserAccessor __parser = __ctrl;注意__ctrl变量是当前的前台页面类对象,而我们可以向当前页面类对象的父类查找(),最终可以看到前台页面类继承自Control

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

这样就清晰多了吧。我们继续看__parser.AddParsedSubObject(__ctrl1);这是将上面的一个方法返回的字符串对象放入当前页面类对象控件集合中去,HtmlHead __ctrl2 = this.__BuildControl__control3();看这个this.__BuildControl__control3();方法,
 [DebuggerNonUserCode]
private HtmlHead __BuildControl__control3()
{
HtmlHead __ctrl = new HtmlHead("head");
HtmlMeta __ctrl1 = this.__BuildControl__control4();
IParserAccessor __parser = __ctrl;
__parser.AddParsedSubObject(__ctrl1);
HtmlTitle __ctrl2 = this.__BuildControl__control5();
__parser.AddParsedSubObject(__ctrl2);
object[] CS$$ = new object[];
CS$$[] = __ctrl;
CS$$[] = 0xab;
CS$$[] = 0x79;
CS$$[] = false;
this.__PageInspector_SetTraceData(CS$$);
return __ctrl;
}
因为前台页面html中<head runat="server">所以后台将这个看做是服务器端控件,为他生成了一个HtmlHead __ctrl = new HtmlHead("head");对象,HtmlMeta __ctrl1 = this.__BuildControl__control4();继续看this.__BuildControl__control4();
 [DebuggerNonUserCode]
private HtmlMeta __BuildControl__control4()
{
HtmlMeta __ctrl = new HtmlMeta();
((IAttributeAccessor) __ctrl).SetAttribute("http-equiv", "Content-Type");
__ctrl.Content = "text/html; charset=utf-8";
object[] CS$$ = new object[];
CS$$[] = __ctrl;
CS$$[] = 0xc2;
CS$$[] = 0x44;
CS$$[] = false;
this.__PageInspector_SetTraceData(CS$$);
return __ctrl;
}
继续以结合前台html代码方式查看

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

这里面是循环嵌套的,难道是不难,只是有些绕。继续贴图

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

图没有全画出来,但意思表达出来了,就是这样,到这里整个一颗控件树就创建出来了。下面我们再返回上面说到的this.ProcessRequest(true, true);这个方法内部,进入this.ProcessRequestMain(includeStagesBeforeAsyncPoint, includeStagesAfterAsyncPoint);方法

 private void ProcessRequestMain(bool includeStagesBeforeAsyncPoint, bool includeStagesAfterAsyncPoint)
{
try
{
HttpContext context = this.Context;
string str = null;
if (includeStagesBeforeAsyncPoint)
{
if (this.IsInAspCompatMode)
{
AspCompatApplicationStep.OnPageStartSessionObjects();
}
if (this.PageAdapter != null)
{
this._requestValueCollection = this.PageAdapter.DeterminePostBackMode();
if (this._requestValueCollection != null)
{
this._unvalidatedRequestValueCollection = this.PageAdapter.DeterminePostBackModeUnvalidated();
}
}
else
{
this._requestValueCollection = this.DeterminePostBackMode();
if (this._requestValueCollection != null)
{
this._unvalidatedRequestValueCollection = this.DeterminePostBackModeUnvalidated();
}
}
string callbackControlID = string.Empty;
if (this.DetermineIsExportingWebPart())
{
if (!RuntimeConfig.GetAppConfig().WebParts.EnableExport)
{
throw new InvalidOperationException(SR.GetString("WebPartExportHandler_DisabledExportHandler"));
}
str = this.Request.QueryString["webPart"];
if (string.IsNullOrEmpty(str))
{
throw new InvalidOperationException(SR.GetString("WebPartExportHandler_InvalidArgument"));
}
if (string.Equals(this.Request.QueryString["scope"], "shared", StringComparison.OrdinalIgnoreCase))
{
this._pageFlags.Set();
}
string str3 = this.Request.QueryString["query"];
if (str3 == null)
{
str3 = string.Empty;
}
this.Request.QueryStringText = str3;
context.Trace.IsEnabled = false;
}
if (this._requestValueCollection != null)
{
if (this._requestValueCollection["__VIEWSTATEENCRYPTED"] != null)
{
this.ContainsEncryptedViewState = true;
}
callbackControlID = this._requestValueCollection["__CALLBACKID"];
if ((callbackControlID != null) && (this._request.HttpVerb == HttpVerb.POST))
{
this._isCallback = true;
}
else if (!this.IsCrossPagePostBack)
{
VirtualPath path = null;
if (this._requestValueCollection["__PREVIOUSPAGE"] != null)
{
try
{
path = VirtualPath.CreateNonRelativeAllowNull(DecryptString(this._requestValueCollection["__PREVIOUSPAGE"], Purpose.WebForms_Page_PreviousPageID));
}
catch
{
this._pageFlags[] = true;
}
if ((path != null) && (path != this.Request.CurrentExecutionFilePathObject))
{
this._pageFlags[] = true;
this._previousPagePath = path;
}
}
}
}
if (this.MaintainScrollPositionOnPostBack)
{
this.LoadScrollPosition();
}
if (context.TraceIsEnabled)
{
this.Trace.Write("aspx.page", "Begin PreInit");
}
if (EtwTrace.IsTraceEnabled(, ))
{
EtwTrace.Trace(EtwTraceType.ETW_TYPE_PAGE_PRE_INIT_ENTER, this._context.WorkerRequest);
}
this.PerformPreInit();
if (EtwTrace.IsTraceEnabled(, ))
{
EtwTrace.Trace(EtwTraceType.ETW_TYPE_PAGE_PRE_INIT_LEAVE, this._context.WorkerRequest);
}
if (context.TraceIsEnabled)
{
this.Trace.Write("aspx.page", "End PreInit");
}
if (context.TraceIsEnabled)
{
this.Trace.Write("aspx.page", "Begin Init");
}
if (EtwTrace.IsTraceEnabled(, ))
{
EtwTrace.Trace(EtwTraceType.ETW_TYPE_PAGE_INIT_ENTER, this._context.WorkerRequest);
}
this.InitRecursive(null);
if (EtwTrace.IsTraceEnabled(, ))
{
EtwTrace.Trace(EtwTraceType.ETW_TYPE_PAGE_INIT_LEAVE, this._context.WorkerRequest);
}
if (context.TraceIsEnabled)
{
this.Trace.Write("aspx.page", "End Init");
}
if (context.TraceIsEnabled)
{
this.Trace.Write("aspx.page", "Begin InitComplete");
}
this.OnInitComplete(EventArgs.Empty);
if (context.TraceIsEnabled)
{
this.Trace.Write("aspx.page", "End InitComplete");
}
if (this.IsPostBack)
{
if (context.TraceIsEnabled)
{
this.Trace.Write("aspx.page", "Begin LoadState");
}
if (EtwTrace.IsTraceEnabled(, ))
{
EtwTrace.Trace(EtwTraceType.ETW_TYPE_PAGE_LOAD_VIEWSTATE_ENTER, this._context.WorkerRequest);
}
this.LoadAllState();
if (EtwTrace.IsTraceEnabled(, ))
{
EtwTrace.Trace(EtwTraceType.ETW_TYPE_PAGE_LOAD_VIEWSTATE_LEAVE, this._context.WorkerRequest);
}
if (context.TraceIsEnabled)
{
this.Trace.Write("aspx.page", "End LoadState");
this.Trace.Write("aspx.page", "Begin ProcessPostData");
}
if (EtwTrace.IsTraceEnabled(, ))
{
EtwTrace.Trace(EtwTraceType.ETW_TYPE_PAGE_LOAD_POSTDATA_ENTER, this._context.WorkerRequest);
}
this.ProcessPostData(this._requestValueCollection, true);
if (EtwTrace.IsTraceEnabled(, ))
{
EtwTrace.Trace(EtwTraceType.ETW_TYPE_PAGE_LOAD_POSTDATA_LEAVE, this._context.WorkerRequest);
}
if (context.TraceIsEnabled)
{
this.Trace.Write("aspx.page", "End ProcessPostData");
}
}
if (context.TraceIsEnabled)
{
this.Trace.Write("aspx.page", "Begin PreLoad");
}
this.OnPreLoad(EventArgs.Empty);
if (context.TraceIsEnabled)
{
this.Trace.Write("aspx.page", "End PreLoad");
}
if (context.TraceIsEnabled)
{
this.Trace.Write("aspx.page", "Begin Load");
}
if (EtwTrace.IsTraceEnabled(, ))
{
EtwTrace.Trace(EtwTraceType.ETW_TYPE_PAGE_LOAD_ENTER, this._context.WorkerRequest);
}
this.LoadRecursive();
if (EtwTrace.IsTraceEnabled(, ))
{
EtwTrace.Trace(EtwTraceType.ETW_TYPE_PAGE_LOAD_LEAVE, this._context.WorkerRequest);
}
if (context.TraceIsEnabled)
{
this.Trace.Write("aspx.page", "End Load");
}
if (this.IsPostBack)
{
if (context.TraceIsEnabled)
{
this.Trace.Write("aspx.page", "Begin ProcessPostData Second Try");
}
this.ProcessPostData(this._leftoverPostData, false);
if (context.TraceIsEnabled)
{
this.Trace.Write("aspx.page", "End ProcessPostData Second Try");
this.Trace.Write("aspx.page", "Begin Raise ChangedEvents");
}
if (EtwTrace.IsTraceEnabled(, ))
{
EtwTrace.Trace(EtwTraceType.ETW_TYPE_PAGE_POST_DATA_CHANGED_ENTER, this._context.WorkerRequest);
}
this.RaiseChangedEvents();
if (EtwTrace.IsTraceEnabled(, ))
{
EtwTrace.Trace(EtwTraceType.ETW_TYPE_PAGE_POST_DATA_CHANGED_LEAVE, this._context.WorkerRequest);
}
if (context.TraceIsEnabled)
{
this.Trace.Write("aspx.page", "End Raise ChangedEvents");
this.Trace.Write("aspx.page", "Begin Raise PostBackEvent");
}
if (EtwTrace.IsTraceEnabled(, ))
{
EtwTrace.Trace(EtwTraceType.ETW_TYPE_PAGE_RAISE_POSTBACK_ENTER, this._context.WorkerRequest);
}
this.RaisePostBackEvent(this._requestValueCollection);
if (EtwTrace.IsTraceEnabled(, ))
{
EtwTrace.Trace(EtwTraceType.ETW_TYPE_PAGE_RAISE_POSTBACK_LEAVE, this._context.WorkerRequest);
}
if (context.TraceIsEnabled)
{
this.Trace.Write("aspx.page", "End Raise PostBackEvent");
}
}
if (context.TraceIsEnabled)
{
this.Trace.Write("aspx.page", "Begin LoadComplete");
}
this.OnLoadComplete(EventArgs.Empty);
if (context.TraceIsEnabled)
{
this.Trace.Write("aspx.page", "End LoadComplete");
}
if (this.IsPostBack && this.IsCallback)
{
this.PrepareCallback(callbackControlID);
}
else if (!this.IsCrossPagePostBack)
{
if (context.TraceIsEnabled)
{
this.Trace.Write("aspx.page", "Begin PreRender");
}
if (EtwTrace.IsTraceEnabled(, ))
{
EtwTrace.Trace(EtwTraceType.ETW_TYPE_PAGE_PRE_RENDER_ENTER, this._context.WorkerRequest);
}
this.PreRenderRecursiveInternal();
if (EtwTrace.IsTraceEnabled(, ))
{
EtwTrace.Trace(EtwTraceType.ETW_TYPE_PAGE_PRE_RENDER_LEAVE, this._context.WorkerRequest);
}
if (context.TraceIsEnabled)
{
this.Trace.Write("aspx.page", "End PreRender");
}
}
}
if ((this._legacyAsyncInfo == null) || this._legacyAsyncInfo.CallerIsBlocking)
{
this.ExecuteRegisteredAsyncTasks();
}
this.ValidateRawUrlIfRequired();
if (includeStagesAfterAsyncPoint)
{
if (this.IsCallback)
{
this.RenderCallback();
}
else if (!this.IsCrossPagePostBack)
{
if (context.TraceIsEnabled)
{
this.Trace.Write("aspx.page", "Begin PreRenderComplete");
}
this.PerformPreRenderComplete();
if (context.TraceIsEnabled)
{
this.Trace.Write("aspx.page", "End PreRenderComplete");
}
if (context.TraceIsEnabled)
{
this.BuildPageProfileTree(this.EnableViewState);
this.Trace.Write("aspx.page", "Begin SaveState");
}
if (EtwTrace.IsTraceEnabled(, ))
{
EtwTrace.Trace(EtwTraceType.ETW_TYPE_PAGE_SAVE_VIEWSTATE_ENTER, this._context.WorkerRequest);
}
this.SaveAllState();
if (EtwTrace.IsTraceEnabled(, ))
{
EtwTrace.Trace(EtwTraceType.ETW_TYPE_PAGE_SAVE_VIEWSTATE_LEAVE, this._context.WorkerRequest);
}
if (context.TraceIsEnabled)
{
this.Trace.Write("aspx.page", "End SaveState");
this.Trace.Write("aspx.page", "Begin SaveStateComplete");
}
this.OnSaveStateComplete(EventArgs.Empty);
if (context.TraceIsEnabled)
{
this.Trace.Write("aspx.page", "End SaveStateComplete");
this.Trace.Write("aspx.page", "Begin Render");
}
if (EtwTrace.IsTraceEnabled(, ))
{
EtwTrace.Trace(EtwTraceType.ETW_TYPE_PAGE_RENDER_ENTER, this._context.WorkerRequest);
}
if (str != null)
{
this.ExportWebPart(str);
}
else
{
this.RenderControl(this.CreateHtmlTextWriter(this.Response.Output));
}
if (EtwTrace.IsTraceEnabled(, ))
{
EtwTrace.Trace(EtwTraceType.ETW_TYPE_PAGE_RENDER_LEAVE, this._context.WorkerRequest);
}
if (context.TraceIsEnabled)
{
this.Trace.Write("aspx.page", "End Render");
}
this.CheckRemainingAsyncTasks(false);
}
}
}
catch (ThreadAbortException exception)
{
HttpApplication.CancelModuleException exceptionState = exception.ExceptionState as HttpApplication.CancelModuleException;
if (((!includeStagesBeforeAsyncPoint || !includeStagesAfterAsyncPoint) || ((this._context.Handler != this) || (this._context.ApplicationInstance == null))) || ((exceptionState == null) || exceptionState.Timeout))
{
this.CheckRemainingAsyncTasks(true);
throw;
}
this._context.ApplicationInstance.CompleteRequest();
ThreadResetAbortWithAssert();
}
catch (ConfigurationException)
{
throw;
}
catch (Exception exception3)
{
PerfCounters.IncrementCounter(AppPerfCounter.ERRORS_DURING_REQUEST);
PerfCounters.IncrementCounter(AppPerfCounter.ERRORS_TOTAL);
if (!this.HandleError(exception3))
{
throw;
}
}
}
内容还是比较多的,但是我们着重依次看几个方法。
1.this.LoadAllState();将表单隐藏域__VIEWSTATE里的数据设置到页面对象ViewState属性
2.this.ProcessPostData(this._requestValueCollection, true);这个与第四个类似,但也有不同。将表单里提交的控件数据设置给页面对象的控件树中对应的控件。要知道这时候前台页面类对象的控件树已经构建完毕了。所以通过这个方法将表单提交的数据封装到控件树上。例如,前台页面<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>文本框中添加test字符串,点击提交的时候,我们在后台类中可以根据TextBox1.Text方式可以获取到这个文本框中的数据(test)。
3.this.LoadRecursive();调用我们在后台的Page_Load中编写的代码,此时我们可以在后台类中访问到浏览器提交的表单控件值了
4.this.ProcessPostData(this._leftoverPostData,false);为在Page_Load中添加的心控件赋值(值来自表单提交),我们可以在Page_Load方法中使用TextBox txt = new TextBox(); txt.ID = "test"; this.form1.Controls.Add(txt);同样可以讲文本框添加到前台页面中去,注意第二个方法中也是将数据封装到控件树,只是一个前后顺序的问题,也是就说在第二个方法(this.ProcessPostData(this._requestValueCollection, true);)封装控件树数据时有些在Page_Load方法中添加的控件(TextBox txt = new TextBox(); txt.ID = "test"; this.form1.Controls.Add(txt);)这时并没有在控件树中,所以数据没办法在第二个方法中封装。这时第四个方法就起作用了。
5.this.RaiseChangeEnvents();执行控件非点击回传事件,例如页面中的DropDownlist
6.this.RaisePostBackEvent(this._requsetValueCollection);执行控件点击回传事件,例如Button
7.this.SaveAllState();将控件的属性状态存入页面的ViewState中
8.this.RenderControl(this.CreatHtmlTextWriter(this.Response.Output));递归调用控件树里的每个控件的Render来生成整个页面的html代码
而在这里也可以解释为什么Page_Load中写Response.Write("测试Page_Load方法中使用Response.Write方法输出");会输出到页面<html>标签前面。因为Response.Write并不是马上输出到浏览器,而是有个缓存区,全部处理完毕,在this.RenderControl才会输出,而html一些代码在this.RenderControl中才会放入缓冲区。前后顺序的问题。
上面忘记提到为什么后台类可以访问前台页面类对象了,我们都知道子类可以访问父类的非私有成员,但是前台类才是子类,为什么父类可以访问子类的东西呢?我们反编译后台类看下
 public class Demo : Page
{
// Fields
protected HtmlForm form1;
protected TextBox TextBox1;
protected HtmlInputText TextBox2; // Methods
public Demo();
protected void Page_Load(object sender, EventArgs e);
} Expand Methods

原来后台类也声明了前台类的属性,这是在编译的时候实现的,而我们在编写的时候可以智能提示出来那就要归结vs的强大了。那就要有人问了,这里只进行了声明,并没有赋值,那我们返回看我们前台页面类构造控件树那里,查看我们前台给了服务器端控件ID属性的控件<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> 我们看这个控件被构建的过程

 [DebuggerNonUserCode]
private TextBox __BuildControlTextBox1()
{
TextBox __ctrl = new TextBox();
base.TextBox1 = __ctrl;
__ctrl.ApplyStyleSheetSkin(this);
__ctrl.ID = "TextBox1";
object[] CS$$ = new object[];
CS$$[] = __ctrl;
CS$$[] = 0x1ac;
CS$$[] = 0x38;
CS$$[] = false;
this.__PageInspector_SetTraceData(CS$$);
return __ctrl;
}

是不是看到了前台类属性赋给后台类属性了呢?

这节内容有些多,又考虑到每个人生成的前台页面类可能不同,虽然内容很简单,但还是将源码上传,这样方便对照。

ReflectorWeb.rar源码