次の方法で共有


HttpHandler ファクトリ

IHttpHandlerFactory インターフェイスを実装するクラスを作成することによって、各 HTTP 要求の新しいハンドラ インスタンスを生成できます。HttpHandler ファクトリを使用して、HTTP GET 要求と HTTP POST 要求に対してそれぞれ異なるハンドラを作成する例を次に示します。一方のハンドラは先の例で説明した同期ハンドラのインスタンスで、もう一方は非同期ハンドラのインスタンスです。

using System;
using System.Web;

namespace Handlers
{
    class HandlerFactory : IHttpHandlerFactory
    {
        public IHttpHandler GetHandler(HttpContext context, string requestType, String url, String pathTranslated)
        {         
            IHttpHandler handlerToReturn;
            if("get" == context.Request.RequestType.ToLower())
            {
                handlerToReturn = new SynchHandler();
            }
            else if("post" == context.Request.RequestType.ToLower())
            {
                handlerToReturn = new AsynchHandler();
            }
            else
            {
                handlerToReturn = null;
            }
            return handlerToReturn;
        }
        public void ReleaseHandler(IHttpHandler handler)
        {
        }
        public bool IsReusable
        {
            get
            {
                // To enable pooling, return true here.
                // This keeps the handler in memory.
                return false;
            }
        }
    }
}


[Visual Basic]
Imports System
Imports System.Web

Namespace Handlers
    Class HandlerFactory
        Implements IHttpHandlerFactory

        Public Function GetHandler(ByVal context As HttpContext, ByVal requestType As String, ByVal url As [String], ByVal pathTranslated As [String]) As IHttpHandler Implements IHttpHandlerFactory.GetHandler            
            Dim handlerToReturn As IHttpHandler
            If "get" = context.Request.RequestType.ToLower() Then
                handlerToReturn = New SynchHandler()
            Else
                If "post" = context.Request.RequestType.ToLower() Then
                    handlerToReturn = New AsynchHandler()
                Else
                    handlerToReturn = Nothing
                End If
            End If
            Return handlerToReturn
        End Function

        Public Sub ReleaseHandler(ByVal handler As IHttpHandler) Implements IHttpHandlerFactory.ReleaseHandler
        End Sub

        Public ReadOnly Property IsReusable() As Boolean
            Get
                ' To enable pooling, return true here.
                ' This keeps the handler in memory.
                Return False
            End Get
        End Property
    End Class
End Namespace

Web.config 内に次のようにエントリを作成して、カスタム HttpHandler ファクトリを登録します。

<configuration>
    <system.web>
        <httpHandlers>
            <add verb="GET,POST" path="*.MyFactory"
                 type="Handlers.HandlerFactory, Handlers" />
        </httpHandlers>
    </system.web>
</configuration>

参照

HttpHandler | HttpHandler の作成