Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
551 views
in Technique[技术] by (71.8m points)

iis - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...