基于Attirbute的ASP.Net控制器路由

时间:2016-05-24 06:45:37

标签: asp.net asp.net-mvc

我知道基于属性的路由在动作级别上工作,但是我可以在控制器级别使用相同的方法来处理以下场景吗?

我有一个名为C1Controller的控制器,但我希望当网址包含C1C2C3然后C1Controller来调用时。如何使用Route属性来实现这一目标?

2 个答案:

答案 0 :(得分:0)

从帖子中得到答案

“最正确的方法是创建一个继承ActionFilterAttribute并覆盖OnActionExecuting方法的类。然后可以在Global.asax.cs中的GlobalFilters中注册”

像:

public class InspectActionFilter : ActionFilterAttribute
{
   public override void OnActionExecuting(ActionExecutingContext filterContext)
   {
       //Check URL for c1, c2 ... and redirect if found
   }
}

要使用它,只需将其添加到global.asax中的全局过滤器:

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
    filters.Add(new HandleErrorAttribute());
    filters.Add(new LogActionFilter());
}

参考:Intercept all calls

ASP.NET MVC 4 intercept all incoming requests

希望这有帮助!

答案 1 :(得分:0)

试试这个

public class TheActionFilter: ActionFilterAttribute
{
    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        var controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
        if (controllerName !="C1" || controllerName !="C1" || controllerName !="C3")
             return;
        var redirectTarget = new RouteValueDictionary
           {{"action", "ActionName"}, {"controller", "ControllerName"}};
        filterContext.Result = new RedirectToRouteResult(redirectTarget);      
        filterContext = new RedirectResult(filterContext.HttpContext.Request.UrlReferrer.AbsolutePath)              // The session you can get from the context like that:
        var session = filterContext.HttpContext.Session;
    }
}

在您的控制器中

[TheActionFilter]
public class BookController : Controller
{
    // Your Action Results
}