HttpModule only on specific MVC route

前端 未结 2 498
醉酒成梦
醉酒成梦 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: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.

提交回复
热议问题