Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpModule only on specific MVC route

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>
like image 471
dotsa Avatar asked Sep 20 '25 12:09

dotsa


1 Answers

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.

like image 100
StockBreak Avatar answered Sep 22 '25 20:09

StockBreak