Search code examples
asp.net-mvchttphandler

what web config settings I need to provide to call this custom handler for all request in MVC app?


I have below handler,

public class ShutdownHandler : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        context.Response.Write("Currently we are down for mantainance");
    }
    public bool IsReusable
    {
        get { return false; }
    }
}

What web config setting is required to call this handler on every request of a Asp.net MVC application??

I tried this with some code, but not able to call on every request,

routes.Add(new Route("home/about", new ShutDownRouteHandler()));

public class ShutDownRouteHandler : IRouteHandler
{
    public IHttpHandler GetHttpHandler(RequestContext requestContext)
    {
        return new ShutdownHandler();
    }
}

Solution

  • You first need a module to map your handler:

    public class ShutDownModule : IHttpModule
    {
        public void Init(HttpApplication app)
        {
            app.PostResolveRequestCache += (src, args) => app.Context.RemapHandler(new ShutDownHandler());
        }
    
        public void Dispose() { }
    }
    

    And then in your web.config:

    <system.webServer>
        <modules>
          <add name="ShutDownModule" type="YourNameSpace.ShutDownModule" />
        </modules>
    </system.webServer>
    

    MVC is an endpoint handler, just like WebForms. You are saying, "hey don't call MVC handler, call this instead".

    For that you need to intercept the mapping that would have occurred and invoked MVC, and instead invoke your own handler. To intercept an event in the pipeline we use HttpModules and register them as above.

    So you're effectively turning MVC off as the request never gets there.