C# Asp.Net Global.asax 访问当前请求的 Page 对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/480623/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Asp.Net Global.asax access to the current requested Page object
提问by John Boker
Is there any way i can access the page object from within the global.asax Application_EndRequest function ?
有什么方法可以从 global.asax Application_EndRequest 函数中访问页面对象吗?
I'm trying to set the text of a label at the end of the request but accessing the page is proving to be more difficult than I thought.
我试图在请求结束时设置标签文本,但事实证明访问该页面比我想象的要困难。
here is what i have that's currently NOT working:
这是我目前无法使用的:
protected void Application_BeginRequest(Object sender, EventArgs e)
{
Context.Items.Add("Request_Start_Time", DateTime.Now);
}
protected void Application_EndRequest(Object sender, EventArgs e)
{
TimeSpan tsDuration = DateTime.Now.Subtract((DateTime)Context.Items["Request_Start_Time"]);
System.Web.UI.Page page = System.Web.HttpContext.Current.Handler as System.Web.UI.Page;
if (page != null)
{
Label label = page.FindControl("lblProcessingTime") as Label;
if (label != null)
{
label.Text = String.Format("Request Processing Time: {0}", tsDuration.ToString());
}
}
}
page is always null here.
页面在这里始终为空。
Thanks in advance.
提前致谢。
采纳答案by Noldorin
It's probably best just to create a BasePage class from which all your pages should inherit. Then you can put the code within the Unload event of the page and there will be no issue.
最好只创建一个 BasePage 类,您的所有页面都应从该类继承。然后你可以把代码放在页面的 Unload 事件中,就不会有问题了。
回答by Steven Behnke
You cannot do this in Application_Start and Application_End.
您不能在 Application_Start 和 Application_End 中执行此操作。
From MSDN:
来自 MSDN:
The Application_Start and Application_End methods are special methods that do not represent HttpApplication events. ASP.NET calls them once for the lifetime of the application domain, not for each HttpApplication instance.
Application_Start 和 Application_End 方法是不代表 HttpApplication 事件的特殊方法。ASP.NET 在应用程序域的生命周期内调用它们一次,而不是为每个 HttpApplication 实例调用它们。
回答by Jim Petkus
At this stage of the request's life cycle the page has already been rendered and the page object is not available anymore. You would need to use an earlier event.
在请求生命周期的这个阶段,页面已经呈现,页面对象不再可用。您将需要使用较早的事件。
That said, I wouldn't recommend this approach as there are a number of issues with it:
也就是说,我不会推荐这种方法,因为它有很多问题:
You are using FindControl. This code will break if the name of the control changes.
您正在使用 FindControl。如果控件的名称更改,此代码将中断。
This code will get run for any request, not just pages and not just the particular pages you need this to run for.
此代码将针对任何请求运行,而不仅仅是页面,而不仅仅是您需要运行的特定页面。
This code should be in a master page or a page base class where you can access the label in a type safe manner.
此代码应位于母版页或页面基类中,您可以在其中以类型安全的方式访问标签。