Access current instance of Page from a static class
Asked Answered
C

3

16

Basic question - is it possible to access the current Page from a static class in ASP.NET?

I am thinking no, as google turns up no results.

Cornucopia answered 22/3, 2010 at 19:46 Comment(1)
Related question: https://mcmap.net/q/237630/-get-current-system-web-ui-page-from-httpcontext/1475331.Ophthalmologist
S
31

Technically you could just get the current IHttpHandler for the request. Since Page implements that, then you could check to see if it is one.

var page = HttpContext.Current.CurrentHandler as Page;

if(page != null){
    // Do something with page
}
Subsistent answered 22/3, 2010 at 19:51 Comment(0)
E
7

You can use HttpContext.CurrentHandler to return the current HttpHandler for the request. A Page class is simply a complex type of HttpHandler.

In order to access anything related to the Page properties though, you'll need to cast the result to type Page.

Honestly though, I would take Jeff's approach if possible, because by injecting the page reference in the method call, your method is much more testable (not to mention reliable, as you can use Page directly). Relying on anything to do with HttpContext tends to make your code untestable. Perhaps you're in a situation where you can't design the method like that, but it would be the way I would prefer to do it.

Exuberant answered 22/3, 2010 at 19:51 Comment(1)
Agreed, I have a strong suspicion that httpcontext is a mess when it comes to threading aswell.Cornucopia
D
4

The simplest way has got to be passing the current page as a parameter to the method you're calling in the static class.

Delbert answered 22/3, 2010 at 19:51 Comment(1)
Yuck! HttpContext.Current it is then, unless you get a chance to refactor.Delbert

© 2022 - 2024 — McMap. All rights reserved.