在web.config中注册httpModules

26

我试图在web.config文件中注册自定义的HttpHandler。 MSDN 的示例显示了一个被注释掉的条目...这个方案并不是很好用。当我取消注释后,会收到一个错误信息:Could not load file or assembly 'HttpModule.cs' or one of its dependencies. The system cannot find the file specified. 文件名为HttpModule.cs,类名为MyHttpModule。目前还没有明确的命名空间。

<httpModules>
     <add name="MyHttpModule" type="MyHttpModule, HttpModule" />
<httpModules>

我相信我正在忽略显而易见的事情。我需要在哪里指定文件路径吗?谢谢。

6个回答

23

我仍在学习许多术语,并需要将其拼写出来。以防您中的任何人需要相同的内容...

例如,如果:

  • 基类名称和项目名称为 TestSite
  • 我的类所在的命名空间是 BusinessLogic
  • 类名为 PageAuthorization

在 Web.config 文件中...

<configuration> 
 <system.web> 
  <httpModules> 
   <add type= "BusinessLogic.PageAuthorization, TestSite" name="PageAuthorization" /> 
  </httpModules> 
 </system.web> 
</configuration>

在我的情况下,我必须标记我的类为IHttpModule。这个类的定义看起来像:

public class PageAuthorization : IHttpModule

3
如果我的模块文件位于网站的App_Code文件夹中,该怎么办? - Jayesh Sorathia

20
如果您正在从 .Net 4.0 GAC 加载自定义模块并且使用的是 IIS 6/7 经典模式,则必须使用以下代码。
 <system.web>
  <httpModules>
  <add name="ClientHttpModule" type="ClientServHttpModule.ClientHttpModule,ClientServHttpModule,Version=1.0.0.0, Culture=neutral, PublicKeyToken=3af8d8e2f9e8b6c3" />
      </httpModules>
 </system.web>

ClientServHttpModule是你自定义模块的命名空间。

可以从sn.exe应用程序获取公钥令牌。

如果你正在运行集成模式,请使用以下代码:

<system.webServer>
        <modules>
            <add name="ClientHttpModule" type="ClientServHttpModule.ClientHttpModule,ClientServHttpModule,Version=1.0.0.0, Culture=neutral, PublicKeyToken=3af8d8e2f9e8b6c3" />
        </modules>
    </system.webServer>

16

type的值应该是以{Class}, {assembly}的格式编写的。

在你的情况下,应该是MyHttpModule, MyDllName

其中MyDllName是编译后DLL的名称。


1
抱歉我的无知,但是我需要将cs文件显式编译成dll才能在web.config中注册它吗? - Praesagus
它可以成为Web项目的一部分,您只需要知道编译后程序集的名称即可。 - Mitchel Sellers
我该如何找到它,然后在注册时应该输入什么? - Praesagus
DLL名称是程序集名称,在项目文件的项目属性中。 - Mitchel Sellers
提供信息,为了非常明确,我必须将 MyDLLName 放在没有尾随的 .dll 的情况下,例如 MyDLLName.dll 不起作用。这对我来说并不明显。 - HeatfanJohn

6

如果你是来寻找在IIS 7及以上版本中运行集成模式的配置信息,请注意以下内容:

<configuration> 
 <system.webServer> 
  <modules> 
   <add type= "BusinessLogic.PageAuthorization, TestSite" name="PageAuthorization" /> 
  </modules> 
 </system.webServer> 
</configuration>

@Rishi 我需要帮助配置system.webserver。如果你们中的任何人能够提供帮助,请查看我的新帖子,网址为http://stackoverflow.com/questions/27354083/web-config-system-webserver-errors。 - te7

3

此外,重要的是要确保您尝试使用的.dll文件位于项目bin文件夹中。我曾经遇到过一个问题,就是将我的模块制作在一个单独的项目中,但忘记了传输.dll文件。


0

我认为system.web中的HttpModules属性适用于ASP 3.5或更早版本。对于ASP 4或更高版本,请使用system.webserver中的模块:

<system.webServer>
    <modules>
        <add name="TestModule"  type="WebApplication1.TestModule, WebApplication1"/>
    </modules>
    <validation validateIntegratedModeConfiguration="false"/>
</system.webServer>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接