Asp.Net Global.asax access to the current requested Page object

15,760

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.

Share:
15,760
gabac
Author by

gabac

.Net, Android, and iOS developer http://www.antiyes.com

Updated on August 01, 2022

Comments

  • gabac
    gabac almost 2 years

    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.

  • Noldorin
    Noldorin over 15 years
    Thanks. I just thought it would be helpful to point out another approach, which may not have been noticed.
  • Ray Booysen
    Ray Booysen over 15 years
    Good call Nolodorin. I'd think this would be the best idea. Even better would be a master page to make sure the label would always be there as it sounds like every page would have the same label.
  • gabac
    gabac over 15 years
    this isnt the Application_Start or Application_End, it's Application_StartRequest and Application_EndRequest.
  • gabac
    gabac over 15 years
    I'll check out this method, the label is on a masterpage and i do have a basepage already defined. the only problem is there is more than one basepage defined so i'll have to do it for each.
  • gabac
    gabac over 15 years
    FindControl wont break if not found, the label will just be null.
  • Noldorin
    Noldorin over 15 years
    That's fine - just put the event handler setup in the constructor of the MasterPage. i.e. this.Page.Unload += ...
  • Pathmapratheep
    Pathmapratheep over 15 years
    Yes the label will be null, the functionality will break. I abhor the use of FindControl. In 99% of the cases it is used it is due to poor design. There will almost always be a way to declare a strongly typed instance of the control you are trying to find.