您的位置:首页 > 理论基础 > 计算机网络

【MVC-自定义HttpModule处理】

2016-04-27 14:38 483 查看
HttpModule是向实现类提供模块初始化和处置事件。

当一个HTTP请求到达HttpModule时,整个ASP.NET Framework系统还并没有对这个HTTP请求做任何处理,也就是说此时对于HTTP请求来讲,HttpModule是一个HTTP请求的“必经之路”,所以可以在这个HTTP请求传递到真正的请求处理中心(HttpHandler)之前附加一些需要的信息在这个HTTP请求信息之上,或者针对截获的这个HTTP请求信息作一些额外的工作,或者在某些情况下干脆终止满足一些条件的HTTP请求,从而可以起到一个Filter过滤器的作用。

下面我们使用自定义的HttpModule模块在用户作出请求进行截获的这个HTTP请求信息作一些额外的工作。

一.创建一个类库项目,里面添加我们的实体类,HttpModule继承IHttpModule接口,实现里面的Dispose方法,和Init事件注册的方法。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace MyHttpModule
{
public class HttpModule : IHttpModule
{

/// <summary>
/// 处置由实现 System.Web.IHttpModule 的模块使用的资源(内存除外)
/// </summary>
public void Dispose() { }

/// <summary>
/// 初始化模块,并使其为处理请求做好准备。
/// </summary>
/// <param name="context"></param>
public void Init(HttpApplication context)
{
context.BeginRequest += context_BeginRequest;//在 ASP.NET 响应请求时作为 HTTP 执行管线链中的第一个事件发生。
context.EndRequest += context_EndRequest;    //在 ASP.NET 响应请求时作为 HTTP 执行管线链中的最后一个事件发生。
}

/// <summary>
/// 在 ASP.NET 响应请求时作为 HTTP 执行管线链中的第一个事件发生。
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void context_EndRequest(object sender, EventArgs e)
{
HttpApplication application = sender as HttpApplication;
HttpContext context = application.Context;
HttpRequest request = application.Request;
HttpResponse response = application.Response;

response.Write("context_EndRequest >> 在 ASP.NET 响应请求时作为 HTTP 执行管线链中的第一个事件发生");
}

/// <summary>
/// 在 ASP.NET 响应请求时作为 HTTP 执行管线链中的最后一个事件发生。
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void context_BeginRequest(object sender, EventArgs e)
{
HttpApplication application = sender as HttpApplication;
HttpContext context = application.Context;
HttpRequest request = application.Request;
HttpResponse response = application.Response;

response.Write("context_BeginRequest >> 在 ASP.NET 响应请求时作为 HTTP 执行管线链中的最后一个事件发生");
}
}
}
二.添加一个MVC的项目,里面新增两个控制器和视图页面

public class HomeController : Controller
{
//
// GET: /Home/

public ActionResult Index()
{
return View();
}
}
public class SonController : Controller
{
//
// GET: /Son/

public ActionResult Index()
{
return View();
}
}
@{
Layout = null;
}

<!DOCTYPE html>

<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<div>
进入Index页面
</div>
</body>
</html>
@{
Layout = null;
}

<!DOCTYPE html>

<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<div>
进入Son页面
</div>
</body>
</html>

IIS上发布成功,在Web.config中的<system.web>下添加配置项,将MyHttpModule.dll库文件放入bin目录:

<httpModules>

<!--<add name="类名" type="命名空间.类名" />

<add name="HttpModule" type="MyHttpModule.HttpModule"/>

</httpModules>

请求发布的地址,页面效果如下:



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: