Jesse
Jesse

Reputation: 599

ASP.NET requested page in Global.asax

I want to be able to globally grab a reference to the Page object that is currently being requested, so I've added a Global.asax file.

Is there any way to do this? I assume it has something to do with the Application_BeginRequest event.

Upvotes: 1

Views: 5699

Answers (4)

jenson-button-event
jenson-button-event

Reputation: 18941

var page = HttpContext.Current.Handler as Page
if(page != null) /// do something with page

PreRequestHandlerExecute should be fine for your purposes (if you don't fancy writing your own HttpModule, which is in fact very easy)

Upvotes: 1

M4N
M4N

Reputation: 96561

You can access the current handler (the page) from global.asax, but not from any stage of the request life cycle. I.e. it is not possible in BeginRequest, but it is possible during PreRequestHandlerExecute:

void Application_PreRequestHandlerExecute(object sender, EventArgs e)
{
    var page = (Context.Handler as System.Web.UI.Page);
}

Note that page might still be null, if the handler is not a page. Also, I'm not sure your approach is the correct one. Maybe you should explain in more detail what you want to attempt?

Upvotes: 7

Oded
Oded

Reputation: 499002

Create a class that is a subclass of Page that does what you want and use this subclass as the base type for all you pages.

public class MyPage : Page
{
 //... override whatever you want, add functionality, whatever
}

All other pages:

public class Index : MyPage
{
   // Automatically get new behaviour
}

Upvotes: 3

Samir Adel
Samir Adel

Reputation: 2499

You have to use http module to catch the every request for each page on your application and do whatever you want with the request.

Upvotes: 1

Related Questions