HttpModule only on specific MVC route

安稳与你 提交于 2019-12-01 23:35:22

问题


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

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

I want this module to only be invoked/handled on the /HandleAzureTask route.

Since this is not a controller, I can't really set the [Authorize] attribute on it; how can I force it only to be invoked/handled if user is authenticated?

I am on ASP.NET MVC 4 and currently have my module added to web.config as such:

<modules>
  <remove name="AzureWebDAVModule" />
  <add name="AzureWebDAVModule" type="VMC.WebDAV.Azure.Module.AzureWebDAVModule, VMC.WebDAV.Azure.Module" />
</modules>

回答1:


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.




回答2:


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 *



来源:https://stackoverflow.com/questions/15798828/httpmodule-only-on-specific-mvc-route

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