2009-12-11 133 views
19

我一直在研究这一点,但没有遇到一个答案 - 有什么办法可以编程方式将HttpHandler添加到ASP.NET网站而无需添加到web.config?以任何方式在.NET中以编程方式添加HttpHandler?

+0

Intresting,ID喜欢看,如果这是可能的自己。好奇的是,为什么不把它添加到web.config?因为这只影响一个网站/应用程序不是所有的IIS – Jammin 2009-12-11 13:26:26

回答

18

通过添加一个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的界面。

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

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

+0

感谢尼克 - 这正是我所期待的。 – 2009-12-11 14:21:26

+0

难以根据我的情况使用这种方法。我试图重新分配处理程序的请求不符合物理文件或任何配置的路由。 PostMapRequestHandler不会在我的情况下触发,因为没有处理程序被发现将请求映射到?看来这些请求触发的最后一个事件是PostResolveRequestCache,如果我尝试在该事件处理器或任何之前的事件处理器中重置context.Handler,它就会被忽略。 – Lobstrosity 2014-08-16 00:29:36

+0

我能够通过调用'context.RemapHandler()'(而不是直接设置'context.Handler')在'BeginRequest'事件处理程序中得到它的工作。 – Lobstrosity 2014-08-16 22:15:34

10

您可以通过使用一个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 Web表单,然后确保你的web应用已在web.config中UrlRouting配置,这里说明:Use Routing with Web Forms

+0

谢谢!正是我需要的...... – rocky 2015-02-15 14:07:55