HttpModule only on specific MVC route

前端 未结 2 478
醉酒成梦
醉酒成梦 2021-01-21 01:45

I have a custom IHttpModule that I would like to only work on a specific route.

For example : http://example.com/HandleAzureTask

I want

相关标签:
2条回答
  • 2021-01-21 02:02

    Why not just create a ordinary folder namned /HandleAzureTask and put a seperate web.config inside that folder with the module registration.

    Then the module will run for all request in that folder.

    To get the authorization to work you can also set the authorization element in the web.config to disallow *

    0 讨论(0)
  • 2021-01-21 02:06

    HttpModules are called on every request (HttpHandlers, instead, can be filtered). If you just want to perform your task only on the selected route, you can do the following:

    Set up a route like this:

    routes.MapRoute(
        name: "AzureWebDAVRoute",
        url: "HandleAzureTask",
        // notice the enableHandler parameter
        defaults: new { controller = "YourController", action = "YourAction", enableHandler = true }
    );
    

    On your module:

    public class AzureWebDAVModule : IHttpModule
    {
        public void Init(HttpApplication context)
        {
            // you can't directly access Request object here, it will throw an exception
            context.PostAcquireRequestState += new EventHandler(context_PostAcquireRequestState);
        }
    
        void context_PostAcquireRequestState(object sender, EventArgs e)
        {
            HttpApplication context = (HttpApplication)sender;
            RouteData routeData = context.Request.RequestContext.RouteData;
    
            if (routeData != null && routeData.Values["enableHandler"] != null)
            {
                // do your stuff
            }
        }
    
        public void Dispose()
        {
            //
        }
    }
    

    Now your task will be performed on the selected route only. Please note that you need the parameter since you can't find the current route by name.

    0 讨论(0)
提交回复
热议问题