代码之家  ›  专栏  ›  技术社区  ›  Ryan Lanciaux

有没有办法在.NET中以编程方式添加httphandler?

  •  21
  • Ryan Lanciaux  · 技术社区  · 15 年前

    我已经对此进行了一些研究,但还没有找到答案——有没有任何方法可以在不添加到web.config的情况下将httphandler程序添加到ASP.NET网站?

    2 回复  |  直到 7 年前
        1
  •  18
  •   Nick Berardi    15 年前

    通过添加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.confi 是的,是隐藏的,似乎不可接近。它基于一个名为 IHttpHandlerFactory .

    更新 这个 IHttphanderFactory公司 可以像任何其他IHttphandler一样使用,只是它用作启动点而不是处理点。请参阅本文。

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

        2
  •  13
  •   Keith K Reed Copsey    12 年前

    您可以使用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,请确保webapp在web.config中具有urlrouting配置,如下所述: Use Routing with Web Forms