关于HttpHandlers 和HttpModules的使用实例[web.config]

web

Creating HttpHandlers and HttpModules
Introduction
ASP.NET allows you to extend its functionality in two main ways :
HttpHandlers
HttpModules
Http handlers are special applications that typically handle files with certain extension. For example when you request a file with extension .asp IIS routes it to ASP processor. But what if I want to handle files with my own extensions say .bipin? Http handlers allow us to do just that. Now, you might be thinking what is the use of a new file extension? Consider a case where you want to generate graphics on the fly. In such cases you will write an Http handler that will do your task. Note that Http handlers are typically called for the specific file extensions they are designed for. If you have worked with ISAPI extensions in past you will find this concept very familiar.
Http modules are similar to Http handlers in that they allow you to tweak with the request and response. However, they are typically executed for every request irrespective of the file type. If you have worked with ISAPI filters before you will find this concept very familiar.

In this article we will see how to create Http Handlers and Http Modules and use them in your ASP.NET pages.

IHttpHandler interface
In order to create Http handler you have to create a class that implements IHttpHandler interface. This interface has one method with following signature :
Sub ProcessRequest(Context as HttpContext)
It also has one read only property with following signature :
Public ReadOnly Property IsReusable() As Boolean

The ProcessRequest method is used to do all of your processing. The context parameter provides access to various objects like Request and Response. The IsReusable property tells whether another requests can use the same instance of Http handler.

Creating the class implementing IHttpHandler
Following is a class that implements IHttpHandler interface.

Public Class MyHttpHandler     
Implements IHttpHandler     Public Sub ProcessRequest(ByVal context As HttpContext)             Implements IHttpHandler.ProcessRequest         context.Response.Write("hello world")     End     Sub Public ReadOnly Property IsReusable() As Boolean             Implements IHttpHandler.IsReusable         Get            Return True         End Get     End Property End Class
Here, we are simply outputting a string "Hello World" for each request handled by this Http handler. You can perform any complex task as per your requirements.

Configuring our Http handler
After you create your Http handler class you should configure your web application so that specific requests will be handled by the handler. To accomplish this you will modify web.config file as follows :

<httpHandlers>
<add verb="*" path="hello.aspx"
type="SampleWebApplication.MyHttpHandler,SampleWebApplication" />
</httpHandlers>

Here, verb attribute indicates GET, POST or * (all). The path attribute  indicates the resource to be handled. In our case we have specific file hello.aspx. Type attribute indicates the fully qualified name of the class and name of assembly respectively.

In case you have to handle different extension say *.bipin then in addition to configuring in web.config (as shown above) you also need to add the extension in IIS. This allows IIS to forward request for specific extension to ASP.NET processor which in turn forwards it to your Http handler.

Testing your http handler
In order to test your Http handler simply add a page named hello.aspx in the project and run it in the browser. You should get "Hello world" displayed in your browser.

IHttpModule interface
In order to create a HttpModule you will first create a class that implements IHttpModule interface. This interface provides following two methods that you must implement :
Sub Init(ByVal app As HttpApplication)
Sub Dispose()
Out of the above two methods the Init() method is of our interest. This method receives an instance of HttpApplication that represents the current application instance. You will attach various event handlers in this method as we will see later on.
Creating the class implementing IHttpModule
Now, let us create a class that implements IHttpModule interface. Here is the complete code for the class :
Public Class MyHttpModule
    Implements IHttpModule

    Public Sub Init(ByVal app As HttpApplication)
    Implements IHttpModule.Init
        AddHandler app.BeginRequest, AddressOf MyBeginRequest
        AddHandler app.EndRequest, AddressOf MyEndRequest
    End Sub

    Public Sub Dispose() Implements IHttpModule.Dispose

    End Sub

    Public Sub MyBeginRequest
    (ByVal s As Object, ByVal e As EventArgs)
        Dim app As HttpApplication
        app = CType(s, HttpApplication)
        app.Response.Write("Hello begin request")
    End Sub

    Public Sub MyEndRequest
    (ByVal s As Object, ByVal e As EventArgs)
        Dim app As HttpApplication
        app = CType(s, HttpApplication)
        app.Response.Write("Hello end request")
    End Sub

End Class

Note how we have used Init() method to attach event handlers to application events. In our example we have set MyBeginRequest method to handle BeginRequest event of HttpApplication and MyEndRequest method handles EndRequest event. This will cause the every request to output "Hello begin request" and "Hello end request" at the start and end of the page respectively.
Add module details in web.config
Prior to using the module we just developed we must inform IIS and ASP.NET abut it. The place to do that is web.config file. Add following section to the file :
<httpModules>
    <add type="SampleWebApplication.MyHttpModule,
    SampleWebApplication"
    name="MyHttpModule" />
</httpModules>

The <httpModules> section is used to publish information about our module. All the modules from this section are loaded by ASP.NET at run time. The type attribute specifies the fully qualified class name and assembly name respectively.
Testing your http module
In order to test our module, create a test web form and put some controls on it. (Remember that if you use Grid layout our messages may not be displayed exactly at the beginning and end. For our testing switch to Flow layout). Now run the web form. You should see our messages at the top and bottom of the web form.

时间: 2024-10-26 05:48:16

关于HttpHandlers 和HttpModules的使用实例[web.config]的相关文章

web.config 关于HttpHandlers 和HttpModules的使用实例【转】

Creating HttpHandlers and HttpModulesIntroductionASP.NET allows you to extend its functionality in two main ways : HttpHandlers HttpModules Http handlers are special applications that typically handle files with certain extension. For example when yo

Asp.Net FckEditor在web.config中配置的具体实例_实用技巧

1.开发网站过程中fck配置:1<appSettings>2    <add key="FCKeditor:BasePath" value="~/fckeditor/"/>3    <add key="FCKeditor:UserFilesPath" value="/[网站名,如:OsChina]/Files/"/>4</appSettings>2.发布网站时修改fck配置:1&

IIS7中web.config给EMLOG设置伪静态规则实例

今天看到论坛上有一位小盆友不会弄IIS7环境下的EMLOG伪静态规则,于是骚包就分享给大家一下这个伪静态规则的代码:  代码如下 复制代码 <?xml version="1.0" encoding="UTF-8"?> <configuration>     <system.webServer>         <rewrite>             <rules>                 <

web.config配置详细说明

(一).Web.Config是以XML文件规范存储,配置文件分为以下格式     1.配置节处理程序声明     特点: 位于配置文件的顶部,包含在<configSections>标志中.     2.特定应用程序配置     特点: 位于<appSetting>中. 可以定义应用程序的全局常量设置等信息.     3.配置节设置     特点: 位于<system.Web>节中,控制Asp.net运行时的行为.     4.配置节组     特点: 用<sect

据说可能是介绍 web.config 最详细的文章。大家参考参考[转]

web|参考 Web.Config  Written on: Nov, 16th 2001. Application("DSN") = "Server=moon; Driver=Sql Server; Database=Store; UID=user; PWD=bingo;" Above declaration in the global.asa file might be familiar to almost all ASP programmers. While

asp.net部署在IIS.net4.0中和.net2.0中出现问题,是使用Jquery调用Webservice,可能是web.config的配置问题

问题描述 .net2.0中的错误信息.net4.0中的错误信息折腾了好久,发现web.config中有了这句,<runtime>......在.net2.0应用池中可用.net4.0中出现错误,去掉这句在.net4.0中可用.net2.0中出现错误.<?xmlversion="1.0"?><configuration><configSections><sectionname="log4net"type="

IIS7.5下的web.config 404配置的一些问题_win服务器

本文介绍一个关于IIS环境下web.config配置的经验问题.在IIS7.5中添加配置404页面时遇到了一些问题,记录如下: 一开始在<customError>下的<error>节点配置404不起作用,由于程序运行在IIS7.5集成模式下,经过MSDN和GOOGLE,发现 需要在<system.webServer>节点中配置,我们知道<system.web>节点是iis7.0之前版本的主要配置节点,由于在II7.0以后IIS管 道处理与ASP.NET管道处

Web.config(应用程序的配置信息)总结_实用技巧

Web.config文件是一个XML文本文件,它用来储存 ASP.NET Web 应用程序的配置信息(如最常用的设置ASP.NET Web 应用程序的身份验证方式),它可以出现在应用程序的每一个目录中.当你通过.NET新建一个Web应用程序后,默认情况下会在根目录自动创建一个默认的Web.config文件,包括默认的配置设置,所有的子目录都继承它的配置设置.如果你想修改子目录的配置设置,你可以在该子目录下新建一个Web.config文件.它可以提供除从父目录继承的配置信息以外的配置信息,也可以重

iis7 配置web.config实现伪静态实现代码

在 IIS7中我们不再需要安装其他组件,通过在 web.config 进行简单的配置即可实现 URL 的伪静态.方法如下: 在 web.config 配置文件的 configuration 节点中加入下边的代码:  代码如下 复制代码 <system.webServer>     <rewrite>         <rules>             <rule name="rulename">                 <