Reputation: 83709
Is there any way i can access the page object from within the global.asax Application_EndRequest function ?
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.
Upvotes: 6
Views: 16140
Reputation: 4508
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.
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.
Upvotes: 0
Reputation: 3344
You cannot do this in Application_Start and Application_End.
From 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.
http://msdn.microsoft.com/en-us/library/ms178473.aspx
Upvotes: 0
Reputation: 147300
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.
Upvotes: 6