Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
565 views
in Technique[技术] by (71.8m points)

asp.net - Any way to add HttpHandler programmatically in .NET?

I've been researching this a bit but haven't come across an answer -- is there any way to programatically add an HttpHandler to an ASP.NET website without adding to the web.config?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

By adding an HttpHandler I assume you mean the configuration files

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

There is a way to control it automatically, by adding the IHttpHandler in directly during the request. So on the PostMapRequestHandler in the Application Lifecycle, you would do the following, in your own custom IHttpModule:

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

And that would automatically set the handler for that request. Obviously you probably want to wrap this in some logic to check for things such as verb, requesting url, etc. But this is how it would be done. Also this is how many popular URL Rewriters work such as:

http://urlrewriter.codeplex.com

Unfortunately though, using the pre built configuration handler that the web.config does, is hidden away and doesn't seem to be accessible. It is based off an interface called IHttpHandlerFactory.

Update The IHttpHandlerFactory can be used just like any other IHttpHandler, only it is used as a launching point instead of a processing point. See this article.

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...