【问题标题】:Any way to add HttpHandler programmatically in .NET?有什么方法可以在.NET 中以编程方式添加 HttpHandler?
【发布时间】:2010-12-25 16:08:09
【问题描述】:

我对此进行了一些研究,但没有找到答案——有没有办法以编程方式将 HttpHandler 添加到 ASP.NET 网站而不添加到 web.config?

【问题讨论】:

  • 有趣,我想看看这是否可能我自己。不过很好奇,为什么不直接将它添加到 web.config 中呢?因为这只会影响一个站点/应用程序而不是所有 IIS

标签: asp.net httphandler


【解决方案1】:

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

<system.web>
    <httpHandlers>...</httpHandler>
</system.web>

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

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

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

http://urlrewriter.codeplex.com

不幸的是,使用pre built configuration handler that the web.config 确实被隐藏起来了,似乎无法访问。它基于一个名为IHttpHandlerFactory 的接口。

更新 IHttpHandlerFactory 可以像任何其他 IHttpHandler 一样使用,只是它被用作启动点而不是处理点。请参阅这篇文章。

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

【讨论】:

  • 谢谢尼克——这正是我想要的。
  • 无法让这种方法适用于我的情况。我尝试为其重新分配处理程序的请求与物理文件或我配置的任何路由都不对应。 PostMapRequestHandler 在我的情况下不会被触发,因为没有找到将请求映射到的处理程序?似乎为这些请求触发的最后一个事件是PostResolveRequestCache,如果我尝试在该事件处理程序或任何更早的事件处理程序中重置context.Handler,它就会被忽略。
  • 我能够通过在BeginRequest 事件处理程序中调用context.RemapHandler()(而不是直接设置context.Handler)来使其工作。
【解决方案2】:

您可以使用 IRouteHandler 类。

  1. 在一个新类中实现 IRouteHandler 接口,并将处理程序作为其GetHttpHandler 方法的结果返回
  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;
    }
}

注册路线:

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

注意:如果使用 Asp.Net Webforms,请确保您的 web 应用在 web.config 中具有 UrlRouting 配置,如下所述:Use Routing with Web Forms

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-09
    相关资源
    最近更新 更多