每个请求都会调用 HttpModules(相反,可以过滤 HttpHandlers)。如果您只想在选定的路线上执行任务,您可以执行以下操作:
设置这样的路线:
routes.MapRoute(
name: "AzureWebDAVRoute",
url: "HandleAzureTask",
// notice the enableHandler parameter
defaults: new { controller = "YourController", action = "YourAction", enableHandler = true }
);
在您的模块上:
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()
{
//
}
}
现在您的任务将仅在选定的路线上执行。请注意,您需要该参数,因为您无法按名称找到当前路线。