从页面访问HttpModule的属性

时间:2012-08-14 09:21:51

标签: asp.net httpmodule

有没有办法从asp.net页面访问HttpModule的属性?

namespace MyHttpModule
{
    public class Module : IHttpModule
    {
        public string M_Property { get; set; }

        public void Init(HttpApplication context)
        {

1 个答案:

答案 0 :(得分:2)

您可以从ApplicationInstance获取活动模块,例如我有一个模块可以在BeginRequest中保存当前的RawUrl:

  public class PlainModule : IHttpModule
  {
    private HttpApplication app = null;    
    public string CurrentRequestUrl;

    public void Init(HttpApplication Context)
    {
      this.app = Context;
      Context.BeginRequest += new System.EventHandler(Begin);
    }

    public void Dispose()
    {
    }

    private void Begin(Object Sender, EventArgs e)
    {
      this.CurrentRequestUrl = this.app.Request.RawUrl;
    }
  }

当然,您必须在web.config中注册您的模块:

  <system.web>
    <httpModules>
      <add name="PlainModule" type="WebApplication1.PlainModule, WebApplication1"/>
    </httpModules>
  </system.web>

然后你可以使用在web配置中注册的名称来获取模块实例,如下所示:

protected void Page_Load(object sender, EventArgs e)
{
  PlainModule pm = (PlainModule)HttpContext.Current.ApplicationInstance.Modules["PlainModule"];
  Response.Write("Current request URL : "  + pm.CurrentRequestUrl);
}