HttpModule 与 Globle.asax

1.HttpModel和Global.asax对比
简单说一下HttpModule可以多个 Global.asax只有一个  

Global.asax 里可以处理Application_Start事件 HttpModule无  

一个虚拟目录只能有一个Global.asax,一般尽量不用,这样方便和别的程序整合
2.Global.asax模块
 void Application_Start(object sender, EventArgs e)  
  {
  // Code that runs on application startup
  }
  void Application_End(object sender, EventArgs e)  
  {
  // Code that runs on application shutdown
  }   
  void Application_Error(object sender, EventArgs e)  
  {  
  // Code that runs when an unhandled error occurs
  }
  void Session_Start(object sender, EventArgs e)  
  {
  // Code that runs when a new session is started
  }
  void Session_End(object sender, EventArgs e)  
  {
  // Code that runs when a session ends.  
  // Note: The Session_End event is raised only when the sessionstate mode
  // is set to InProc in the Web.config file. If session mode is set to StateServer  
  // or SQLServer, the event is not raised.
  }
3.HttpModule实现
创建一个类实现HttpModule接口,在web.config中设置
<httpModules>
  <add type="HttpControler" name="HttpControler"/>
</httpModules>

其中“HttpControler”为创建类名称,里面要实现init和dispose方法


====================================================================

引自msdn:

HTTP 模块与 Global.asax 文件
可以在应用程序的 Global.asax 文件中实现模块的许多功能,这使您可以响应应用程序事件。但是,模块相对于 Global.asax 文件具有如下优点:模块可以进行封装,因此可以在创建一次后在许多不同的应用程序中使用。通过将它们添加到全局程序集缓存 (GAC) 并将它们注册到 Machine.config 文件中,可以跨应用程序重新使用它们。有关更多信息,请参见全局程序集缓存。

但是,使用 Global.asax 文件有一个好处,那就是您可以将代码放在其他已注册的模块事件(如 Session_Start 和 Session_End 方法)中。此外,Global.asax 文件还允许您实例化可在整个应用程序中使用的全局对象。

当您需要创建依赖应用程序事件的代码并且希望在其他应用程序中重用模块时,或者不希望将复杂代码放在 Global.asax 文件中时,应当使用模块。当您需要创建依赖应用程序事件的代码但不需要跨应用程序重用它时,或者需要订阅不可用于模块的事件(如 Session_Start)时,应当将代码放在 Global.asax 文件中。


===================================================================

引自codebetter.com :

Global.asax? Use HttpModules Instead!

In a previous post, I talked about HttpHandlers – an underused but incredibly useful feature of ASP.NET. Today I want to talk about HttpModules, which are probably more common than HttpHandlers, but could still stand to be advertised a bit more.

HttpModules are incredibly easy to explain, so this will hopefully be a short-ish post. Simply put, HttpModules are portable versions of the global.asax. So, in your HttpModule you’ll see things like BeginRequest, OnError, AuthenticateRequest, etc. Actually, since HttpModules implement IHttpModule, you actually only get Init (and Dispose if you have any cleanup to do). The Init method passes in the HttpApplication which lets you hook into all of those events. For example, I have an ErrorModule that I use on most projects:

using System;
using System.Web;
using log4net;

namespace Fuel.Web
{
 public class ErrorModule : IHttpModule
 {
  #region IHttpModule Members
  public void Init(HttpApplication application)
  {
   application.Error += new EventHandler(application_Error);  
  }      
  public void Dispose() { }
  #endregion

  public void application_Error(object sender, EventArgs e)
  {
    //handle error
  }
 }
}

Now, the code in my error handler is pretty simple:

HttpContext ctx = HttpContext.Current;
//get the inner most exception
Exception exception;
for (exception = ctx.Server.GetLastError(); exception.InnerException != null; exception = exception.InnerException) { }
if (exception is HttpException && ((HttpException)exception).GetHttpCode() == 404)
{
 logger.Warn(“A 404 occurred”, exception);
}
else
{
 logger.Error(“ErrorModule caught an unhandled exception”, exception);
}

I’m just using a log4net logger to log the exception, if it’s a 404 I’m just logging it as a warning.

You can do this just as easily with a global.asax, but those things aren’t reusable across projects. That of course means that you’ll end up duplicating your code and making it hard to manage. With my ErrorModule class, I just put it in a DLL, drop it in my bin folder and add a couple lines to my web.config under <system.web>:

<httpModules>
 <add  name=”ErrorModule” type=”Fuel.Web.ErrorModule, Fuel.Web” />
</httpModules>

And voila, I have a global error in place.

In almost all cases, you should go with HttpModules over global.asax because they are simply more reusable. As another example, my localization stuff uses an HttpModule as the basis for adding a multilingual framework to any application. Simply drop the DLL in the bin and add the relevant line in your web.config and you’re on your way. Here’s the important code from that module:

public void Init(HttpApplication context)
{
 context.BeginRequest += new EventHandler(context_BeginRequest);
}
public void Dispose() {}
private void context_BeginRequest(object sender, EventArgs e)
{
 HttpRequest request = ((HttpApplication) sender).Request;
 HttpContext context = ((HttpApplication)sender).Context;
 string applicationPath = request.ApplicationPath;
 if(applicationPath == “/”)
 {
    applicationPath = string.Empty;
 }
 string requestPath = request.Url.AbsolutePath.Substring(applicationPath.Length);
 //just a function that parses the path for a culture and sets the CurrentCulture and CurrentUICulture
 LoadCulture(ref requestPath);
 context.RewritePath(applicationPath + requestPath);
}

If you are developing a shrink-wrap product, you don’t have a choice but to use HttpModules, because the last thing you want is to ship a global.asax which the user must use, overwriting the code in his own global.asax.

The only time you want to use Global.asax is when using OutputCaching with the VaryByCustom property. As far as I know, the GetVaryByCustomString function _must_ be placed in the global.asax file.

Anyways, switching from Global.asax to HttpModules is pretty straightforward. So I encourage you to look at where it makes sense (ie, where you see the potential for reuse across applications) and make it so.


猜你喜欢

转载自blog.csdn.net/os2046/article/details/7714373