Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what alternatives are there to using global.asax?

I am using my own custom authentication with IIS, and I want the server on every page load (no matter what type of file) to first check the Application variable to see if the user is authenticated and authorized to see the site. In global.asax this could be:

void Application_Start(Object Sender, EventArgs e)
{
  if(Application["username"] == null)
  {
    Response.redirect("login.aspx");
  }
}

The problem is that this site has multiple sub-roots. That is, http://example.com/site1 is a completely different website from http://example.com/site2 . Therefore, I would like said Application_Start function to work on site1 but not affect site2.

If global.asax was customizable at directory level, then this wouldn't be a problem. But since there is only one global.asax per server I cannot implement this solution.

What alternatives are there to global.asax? or can global.asax be different somehow for each directory?

like image 274
Alexander Bird Avatar asked Nov 21 '08 04:11

Alexander Bird


1 Answers

HttpModules are an alternative to global.asax

(see also https://www.codeguru.com/csharp/.net/net_asp/article.php/c19389/HTTP-Handlers-and-HTTP-Modules-in-ASPNET.htm
http://codebetter.com/blogs/karlseguin/archive/2006/06/12/146356.aspx )

HttpModules are registered in web.config; which, conveniently, is customizable at directory level. So every directory can have its own unique set of modules (that are inherited in lower directories). All modules have the same functionality as those found in global.asax .

Basically, every page request gets passed through every registered module before it ever gets to the actual page code itself. This happens regardless of what kind of request it is:

"page.aspx"    "page.html"
    |             |
(   |  module 1   |  )
(   |  module 2   |  )
(   |  module 3   |  )
    V             V
(handler 1) (handler 2)

((a much better picture and description can be found at https://www.codeguru.com/csharp/.net/net_asp/article.php/c19389/HTTP-Handlers-and-HTTP-Modules-in-ASPNET.htm ))

So then all you need to do is define your code as a module instead of in global.asax . If the user isn't authenticated, then: response.redirect("login.aspx") will stop control from ever reaching the handler and parsing/returning/running the requested page.

It's a little more complicated than that, so a better description/tutorial can be found at the codeguru website.

like image 125
Alexander Bird Avatar answered Oct 17 '22 23:10

Alexander Bird