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

HttpModule动态注册与配置注册

2017-09-28 00:13 369 查看

一:动态注册HttpModule 

参考资料:MVC源码解析 - 配置注册 / 动态注册 HttpModule

第一步:创建一个项目,这里我们创建一个一般处理程序(当然你也可以创建其他的应用程序,如MVC)

第二步:创建一个我自己的HttpModule类

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

namespace WebApplication2
{
public class MyModule:IHttpModule //我自己创建了一个MyModule类,继承了IHhttpModule
{
public void Dispose()
{
throw new NotImplementedException();
}

public void Init(HttpApplication context)
{
context.BeginRequest += context_BeginRequest;
}

void context_BeginRequest(object sender, EventArgs e)
{
var app = sender as HttpApplication;
app.Response.Write("执行了MyModule");
}
}
}
第三步:在项目中新建一个类,这个类用户动态注册我们的HttpModule ,我们就取名叫PreApplicationStartCode类吧

using Microsoft.Web.Infrastructure.DynamicModuleHelper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WebApplication2
{

public class PreApplicationStartCode
{
private static bool hasLoaded;
public static void PreStart()
{
if (!hasLoaded)
{
hasLoaded = true;
//注意这里的动态注册,此静态方法在Microsoft.Web.Infrastructure.DynamicModuleHelper
DynamicModuleUtility.RegisterModule(typeof(MyModule));

}
}
}
}


第四步:用法

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

//将这个特性标签打WebApplication2 这个引用程序上面,这样WebApplication2应用程序下面的所有页面执行的时候后会先执行到我们自己的MyModule
//注意这个PreStart就是PreApplicationStartCode类下面的静态PreStart()方法名称
[assembly: PreApplicationStartMethod(typeof(WebApplication2.PreApplicationStartCode), "PreStart")]
namespace WebApplication2
{
/// <summary>
/// Handler1 的摘要说明
/// </summary>
public class Handler1 : IHttpHandler
{

public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
context.Response.Write("\nHello World");
}

public bool IsReusable
{
get
{
return false;
}
}
}
}


效果



二:通过配置的方式来注册我们自己的HttpModule

第一步,第二步都一样,只是这里不需要第三步,第四步也不许在应用程序上面加特性

打开Web.config文件

<configuration>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
</system.web>
<system.webServer> <!--在这里添加一个system.webServer节点-->
<modules> <!--添加modules节点-->
<add name="MyModule" type="WebApplication2.MyModule,WebApplication2"/><!--配置我们自己的Module-->
</modules>
</system.webServer>
</configuration>


浏览我们的Handler1.ashx

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace WebApplication2 //注意,配置的形式,这里不需要加特性标签
{
/// <summary>
/// Handler1 的摘要说明
/// </summary>
public class Handler1 : IHttpHandler
{

public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
context.Response.Write("\nHello World");
}

public bool IsReusable
{
get
{
return false;
}
}
}
}
效果一样

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