有什么方法可以在.NET中以编程方式添加HttpHandler吗?

Rya*_*aux 21 asp.net httphandler

我一直在研究这个但是没有得到答案 - 有没有办法以编程方式将HttpHandler添加到ASP.NET网站而不添加到web.config?

Nic*_*rdi 18

通过添加HttpHandler我假设你的意思是配置文件

<system.web>
    <httpHandlers>...</httpHandler>
</system.web>
Run Code Online (Sandbox Code Playgroud)

有一种方法可以通过IHttpHandler在请求期间直接添加in 来自动控制它.因此,在Application Lifecycle中PostMapRequestHandler中,您将在自己的自定义中执行以下操作IHttpModule:

private void context_PostMapRequestHandler(object sender, EventArgs e)
{
    HttpContext context = ((HttpApplication)sender).Context;
    IHttpHandler myHandler = new MyHandler();
    context.Handler = myHandler;
}
Run Code Online (Sandbox Code Playgroud)

这将自动设置该请求的处理程序.显然,您可能希望将其包含在一些逻辑中以检查诸如动词,请求URL等内容.但这就是如何完成的.这也是有多少流行的URL重写器工作,例如:

http://urlrewriter.codeplex.com

不幸的是,使用web.confi所做的预构建配置处理程序,它被隐藏起来,似乎无法访问.它基于一个名为的接口IHttpHandlerFactory.

更新IHttpHandlerFactory可用于就像任何其他的IHttpHandler,只有它被用来作为一个出发点,而不是一个加工点.看到这篇文章.

http://www.uberasp.net/getarticle.aspx?id=49


Kei*_*h K 13

您可以使用IRouteHandler类.

  1. 在新类中实现IRouteHandler接口,并根据其GetHttpHandler方法返回hander
  2. 注册您的路线/

实现IRouteHandler

public class myHandler : IHttpHandler, IRouteHandler
{
    public bool IsReusable
    {
        get { return true; }
    }

    public void ProcessRequest(HttpContext context)
    {
        // your processing here
    }

    public IHttpHandler GetHttpHandler(RequestContext requestContext)
    {
        return this;
    }
}
Run Code Online (Sandbox Code Playgroud)

注册路线:

//from global.asax.cs
protected void Application_Start(object sender, EventArgs e)
{
    RouteTable.Routes.Add(new Route
    (
        "myHander.axd",
        new myHandler()
    ));
}
Run Code Online (Sandbox Code Playgroud)

注意:如果使用Asp.Net Webforms,请确保您的webapp在web.config中具有UrlRouting配置,如下所述:使用Web表单路由