How to obtain a reference to the default ASP.NET page handler or web-services handler?

时光怂恿深爱的人放手 提交于 2019-12-04 07:27:04

I would have thought the easiest way would be for your class to inherit from System.Web.UI.PageHandlerFactory and then in an else clause just call base.GetHandler().

public sealed class TotalHandlerFactory : System.Web.UI.PageHandlerFactory
{
    public IHttpHandler GetHandler(HttpContext context, string requestType, string url, string pathTranslated)
    {
        if (some condition is true)
            return new MySpecialHttpHandler();
        else
            return base.GetHandler(context, requestType, url, pathTranslated)
    }
}

I had the same problem, and seems that doing that is not possible using an HttpHandlerFactory.

But, I found a workaround that solved the problem: Using an HttpModule to filter which requests should go to my custom HttpHandler:

First, remove the any reference to your HttpHandler from the web.config.

Then, add a reference to the following HttpModule inside the <Modules> section:

public class MyHttpModule : IHttpModule
{
    public void Dispose() { }

    public void Init(HttpApplication application)
    {
        application.PostAuthenticateRequest += new EventHandler(application_PostAuthenticateRequest);
    }

    void application_PostAuthenticateRequest(object sender, EventArgs e)
    {
        var app = sender as HttpApplication;
        var requestUrl = context.Request.Url.AbsolutePath;

        if (requestUrl "meets criteria")
        {
            app.Context.RemapHandler(new MyHttpHandler());
        }
    }

}

Finally, assume at your HttpHandler that all the incoming request fulfill your criteria, and handle there all the requests.

Without knowing all of your requirements, it sounds like a HttpModule is a more suitable solution for your problem.

It is not possible to do this in the general case.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!