`
luliangok
  • 浏览: 816926 次
文章分类
社区版块
存档分类
最新评论

注册HttpHandler

 
阅读更多

在创建了自定义 HttpHandler 后,必须配置 ASP.NET 以便将传入的对特定 URL 的 HTTP 请求映射到处理程序。以下过程描述所需步骤。

注册 HttpHandler

  1. 在应用程序的虚拟根目录下的 /bin 目录中编译和部署 HttpHandler 的 .NET 类。
  2. 在应用程序的 Web.config 配置文件中注册同步或异步的 HttpHandler。以下示例将所有 HTTP 请求映射到 Myhandler.dll 文件中 MyHandler 程序集的 MyHandler.New 类和 MyHandler.Fin 类。
    <configuration>
        <system.web>
            <httpHandlers>
                <add verb="*" path="MyHandler.New" 
                   type="MyHandler.New, MyHandlerAssembly" />
                <add verb="*" path="*.myNewFileNameExtension" 
                   type="MyHandler.Fin, MyHandlerAssembly" />
            </httpHandlers>
        <system.web>
    </configuration>

    <httpHandlers> 配置节中的项具有三个属性,如下表中所示。

    属性 说明
    路径 路径属性可以包含单个 URL 路径或简单的通配符字符串(例如 *.aspx)。
    类型 指定逗号分隔的类/程序集组合。ASP.NET 首先在应用程序的专用 /bin 目录中搜索程序集 DLL,然后在系统程序集缓存中搜索程序集 DLL。
    谓词 谓词列表可以是逗号分隔的 HTTP 方法列表(例如“GET, PUT, POST”),也可以是开始脚本映射(例如通配符 * [星号])。
  3. 确保将 HttpHandler 文件扩展名注册到 Internet 信息服务 (IIS) 中。

HttpHandler 示例

本节提供下列代码示例:

同步 HttpHandler

以下代码说明如何在 ASP.NET 应用程序中处理对特定的 MyApp.MyHello URL 的请求。接下来,将显示注册 HttpHandler 所需的配置文件更改。

[C#]
using System.Web;
public class HelloWorldHandler : IHttpHandler {
    public void ProcessRequest(HttpContext context) {
        HttpRequest Request = context.Request;
        HttpResponse Response = context.Response;
        // A file ending in .MyHello need not exist. This handler executes
        // whenever a file ending in .MyHello is requested.
        Response.Write("<html>");
        Response.Write("<body>");
        Response.Write("<h1> Hello from Synchronous custom handler. </h1>");
        Response.Write("</body>");
        Response.Write("</html>");
    }
    public bool IsReusable {
        // To enable pooling, return true here.
        // This keeps the handler in memory.
        get { return false; }  
    }
}

[VisualBasic]
Imports System.Web

Public Class HelloWorldHandler
    Implements IHttpHandler

    Public Sub ProcessRequest(ByVal context As System.Web.HttpContext) Implements System.Web.IHttpHandler.ProcessRequest
        Dim request As HttpRequest = context.Request
        Dim response As HttpResponse = context.Response
        ' A file named ending in .MyHello need not exist. This handler 
        ' executes whenever a file ending in .MyHello is requested.
        response.Write("<html>")
        response.Write("<body>")
        response.Write("<h1> Hello from Synchronous custom handler. </h1>")
        response.Write("</body>")
        response.Write("</html>")
    End Sub

    Public ReadOnly Property IsReusable() As Boolean Implements System.Web.IHttpHandler.IsReusable
        Get
            Return False
        End Get
    End Property
End Class

通过在 Web.config 中创建项来注册自定义 HttpHandler,如下所示:

<configuration>
    <system.web>
        <httpHandlers>
           <add verb="*" path="*.MyHello" 
                type="HelloWorldHandler,httpruntime" /> 
        </httpHandlers>
    </system.web>
</configuration>

异步 HttpHandler

以下代码说明如何在 ASP.NET 应用程序中注册和处理对特定的 *.MyAsynch URL 的请求。在这种情况下,处理程序启动一个很耗时的进程,在若干时刻向用户发送响应以指示进程。接下来,将显示注册 HttpHandler 所需的配置文件更改。

[C#]
using System;
using System.Web;
using System.Threading;

namespace Handlers
{
    class AsynchHandler : IHttpAsyncHandler
    {
        private HttpContext _context;
        public bool IsReusable
        {
            get
            {
                 // To enable pooling, return true here.
                 // This keeps the handler in memory.
                 return false;
            }
        }

        public IAsyncResult BeginProcessRequest(HttpContext context,            AsyncCallback cb, Object extraData)
        {
            // Now do something that might take a while.
            MyAsynchOperation asynch = new MyAsynchOperation(cb, context);
            asynch.KickOffThread();

            context.Response.Write("BeginProcessRequest. Just kicked off a Thread.<br>");
            context.Response.Flush();

            // Signal the application that asynchronous 
            // processing is being performed. 
            SomeResult asynchForBegin = new SomeResult();

            // Processing is not synchronous.
            asynchForBegin.SetSynch(false);

            // Processing is not complete.
            asynchForBegin.SetCompleted(false);

            _context = context;
            return new SomeResult();
        }

        public void EndProcessRequest(IAsyncResult result)
        {
            _context.Response.Write("EndProcessRequest called.<br>");
        }

        // This method is required but is not called.
        public void ProcessRequest(HttpContext context)
        {
        }

    }//end class

    public class SomeResult : IAsyncResult
    {

    /*
    An instance of this class is returned to the application.
    This class lets the application know how the BeginEventHandler method     
    has been handled. The application checks the CompletedSynchronously     
    method.
    */

        private bool _blnIsCompleted = false;
        private Mutex myMutex = null;
        private Object myAsynchStateObject = null;
        private bool _blnCompletedSynchronously = false;

        public void SetCompleted(bool blnTrueOrFalse)
        {
            _blnIsCompleted = blnTrueOrFalse;
        }

        public void SetSynch(bool blnTrueOrFalse)
        {
            _blnCompletedSynchronously = blnTrueOrFalse;
        }

        public bool IsCompleted
        {
            // This is not called by the application. 
            // However, set it to true. 
            get { return _blnIsCompleted; }
        }

        public WaitHandle AsyncWaitHandle
        {
            // The application does not call this method.         
            get { return myMutex; }
        }

        public Object AsyncState
        {  
            // The application does not call this method because
            // null is passed in as the last parameter to 
            // BeginEventHandler.
            get { return myAsynchStateObject; }
       }

        public bool CompletedSynchronously
        {
            // The application wants to know if this is synchronous.
            // Return true if the Begin method was called synchronously.
            get { return _blnCompletedSynchronously; }
        }
    }
}

[VisualBasic]
Imports System
Imports System.Web
Imports System.Threading

Namespace handler

    Public Class AsynchHandler
        Implements IHttpAsyncHandler

        Private _context As HttpContext
        Public ReadOnly Property IsReusable() As Boolean Implements System.Web.IHttpAsyncHandler.IsReusable
            Get
                Return False
            End Get
        End Property

        Public Function BeginProcessRequest(ByVal context As System.Web.HttpContext, ByVal cb As System.AsyncCallback, ByVal extraData As Object) As System.IAsyncResult Implements System.Web.IHttpAsyncHandler.BeginProcessRequest
            Dim asynch As New MyAsynchOperation(cb, context)
            asynch.KickOffThread()

            context.Response.Write("BeginProcessRequest. Just kicked off a Thread.<br>")
            context.Response.Flush()
            ' Signal the application that asynchronous 
            ' processing is being performed. 
            Dim asynchForBegin As New SomeResult()

           ' Processing is not synchronous.
            asynchForBegin.SetSynch(False)

           ' Processing is not complete.
            asynchForBegin.SetCompleted(False)

            _context = context

            Return New SomeResult()
        End Function


        Public Sub EndProcessRequest(ByVal result As System.IAsyncResult) Implements System.Web.IHttpAsyncHandler.EndProcessRequest
            _context.Response.Write("EndProcessRequest called.<br>")
        End Sub

        Public Sub ProcessRequest(ByVal context As System.Web.HttpContext) Implements System.Web.IHttpAsyncHandler.ProcessRequest
            ' Ths is required but is not called.
        End Sub
    End Class

    Class SomeResult
        Implements IAsyncResult

        Private _blnIsCompleted As Boolean = False
        Private myMutex As Mutex = Nothing
        Private myAsynchStateObject As Object = Nothing
        Private _blnCompletedSynchronously As Boolean = False

        Public Sub SetCompleted(ByVal blnTrueOrFalse As Boolean)
            _blnIsCompleted = blnTrueOrFalse
        End Sub

        Public Sub SetSynch(ByVal blnTrueOrFalse As Boolean)
            _blnCompletedSynchronously = blnTrueOrFalse
        End Sub

        Public ReadOnly Property AsyncState() As Object Implements System.IAsyncResult.AsyncState
            Get
                Return myAsynchStateObject
            End Get
        End Property

        Public ReadOnly Property AsyncWaitHandle() As System.Threading.WaitHandle Implements System.IAsyncResult.AsyncWaitHandle
            Get
                Return myMutex
            End Get
        End Property

        Public ReadOnly Property CompletedSynchronously() As Boolean Implements System.IAsyncResult.CompletedSynchronously
            Get
                Return _blnCompletedSynchronously
            End Get
        End Property

        Public ReadOnly Property IsCompleted() As Boolean Implements System.IAsyncResult.IsCompleted
            Get
                Return _blnIsCompleted
            End Get
        End Property
    End Class
End Namespace

通过在 Web.config 中创建项来注册自定义异步 HttpHandler,如下所示:

<configuration>
    <system.web>
        <httpHandlers>
            <add verb="GET,POST" path="*.MyAsynch"
                 type="Handlers.AsynchHandler, Handlers" />
        </httpHandlers>
    </system.web>
</configuration>
分享到:
评论

相关推荐

    HttpModule和httpHandler学习例子

    1. **注册HttpHandler**:同样在`Web.config`中,我们可以在`system.web/httpHandlers`节中配置处理器,指定其扩展名和处理程序类型。 2. **实现IHttpHandler**:自定义的HttpHandler需要实现`IHttpHandler`接口,...

    httphandler项目样板的压缩文件

    开发者可以通过这个模板了解如何注册HTTPHandler,以及如何编写处理特定HTTP请求的代码。 描述中的“httphandler项目样板”进一步强调了这个压缩文件的主要功能,即提供了一个基础的HTTPHandler的实现,以便开发者...

    防盗链模块,(HttpHandler+Apache技术)

    通过创建并注册HttpHandler,我们可以对特定的HTTP请求类型做出响应,比如处理特定的URL路径或HTTP方法。在防盗链的应用中,HttpHandler可以用来检查每个请求的来源,确保它们都符合预期的访问规则。 首先,我们...

    ASP.NET源码——利用HttpHander生成HTML页的实例.zip

    **注册HttpHandler** 创建了HttpHandler后,需要在ASP.NET配置文件(web.config)中进行注册,以便服务器知道何时使用这个处理器。在`&lt;system.webServer&gt;`或`&lt;system.web&gt;`部分(取决于你的ASP.NET版本),添加以下...

    HttpHandler的基本路由

    在ASP.NET MVC中,我们不能直接通过路由注册HttpHandler,但可以通过IIS或Web.config来配置。在Web.config中,可以添加以下代码来映射URL到我们的HttpHandler: ```xml *" type="YourNamespace.MyCustomHandler...

    ASp.NET水印图片小例

    1. **注册HttpHandler**:在Web.config文件中,我们需要配置HttpHandler,使其能够响应特定的URL模式,例如“/watermark.ashx”。 2. **处理请求**:在HttpHandler的`ProcessRequest`方法内,首先读取请求参数,...

    商业编程-源码-利用HttpHander生成HTML页的实例.zip

    3. 注册HttpHandler。在Web.config配置文件中,我们需要添加一个`&lt;httpHandlers&gt;`或`&lt;handlers&gt;`(对于ASP.NET 4.0及更高版本)节点,配置自定义HttpHandler,指定其处理的请求路径和类名。 4. 在HTTP请求到达匹配...

    测试代码:Asp.Net底层解析(五)——HttpHandler详解

    此外,HttpHandler可以通过注册到`web.config`文件中来启用。在`&lt;system.web&gt;`节下添加`&lt;httpHandlers&gt;`元素,或者在ASP.NET 4.0及更高版本中,在`&lt;system.webServer&gt;`节下添加`&lt;handlers&gt;`元素,配置对应的...

    ASP.NET架构分析(二)

    注册HttpHandler通常是在`Web.config`或`machine.config`文件中完成的。在配置文件的`&lt;httpHandlers&gt;`节中,我们可以添加一个新的`&lt;add&gt;`元素,指定HTTP动词(verb)、请求路径(path)以及处理程序的类型。在示例中...

    HttpHandler做图片水印

    4. 在Web.config文件中注册自定义的HttpHandler。我们需要在`&lt;httpHandlers&gt;`或`&lt;system.webServer&gt;&lt;handlers&gt;`部分添加相应的配置项,指定URL模式和对应的HttpHandler类。 接下来,我们需要实现图片水印的逻辑。这...

    利用httphandler实现网站伪静态

    在`Web.config`文件中,我们需要注册自定义的HttpHandler。这可以通过添加`&lt;httpHandlers&gt;`或`&lt;system.webServer&gt;&lt;handlers&gt;`节点来完成,具体取决于使用的ASP.NET版本(ASP.NET 2.0/3.5使用`&lt;httpHandlers&gt;`,4.0...

    Protect Files and Folders Using HttpHandlers in ASP.NET

    2. **注册HttpHandler** 创建了`HttpHandler`后,需要在Web.config文件中注册它。添加以下配置: ```xml *" path="protected/*" type="YourNamespace.ProtectedFileHandler, YourAssemblyName"/&gt; ``` ...

    .net使用一般处理程序生成验证码

    7. **注册HttpHandler** - 在`web.config`文件中,需要添加一个`&lt;httpHandlers&gt;`节,声明我们的HttpHandler,指定其路径和类名。 8. **在网页中使用** - 在HTML代码中,可以使用`&lt;img&gt;`标签引用这个HttpHandler的...

    C#防盗链实现入门级别

    6. 注册HttpHandler:最后,在`web.config`文件中注册我们创建的HttpHandler,使其能够处理特定的请求,如所有`.jpg`、`.png`等图片文件。 ```xml *.jpg" type="YourNamespace.ImageProtectionHandler, ...

    ASP.NET架构详解HttpHandler和HttpModule高清PDF文字版

    在这个主题中,我们将深入探讨ASP.NET架构中的两个关键组件:HttpHandler和HttpModule。 **HttpHandler**是ASP.NET处理HTTP请求的核心组件。每个HTTP请求都会被路由到一个特定的HttpHandler,它负责处理特定类型的...

    异步Httphandler

    **注册异步HttpHandler** 为了使异步HttpHandler生效,需要在Web.config文件中进行配置。在`&lt;system.web&gt;`节下添加一个`&lt;httpHandlers&gt;`或`&lt;handlers&gt;`(针对ASP.NET MVC)元素,并指定处理器的类型: ```xml &lt;!-- ...

    ajax+jquery+ashx实现上传文件

    在ASP.NET环境中,我们需要在Global.asax.cs文件中注册HttpHandler,然后创建一个名为UploadHandler.ashx.cs的类来处理请求: ```csharp // 在Global.asax.cs中注册HttpHandler public class Global : System.Web....

Global site tag (gtag.js) - Google Analytics