我知道基于属性的路由在动作级别上工作,但是我可以在控制器级别使用相同的方法来处理以下场景吗?
我有一个名为C1Controller
的控制器,但我希望当网址包含C1
或C2
或C3
然后C1Controller
来调用时。如何使用Route
属性来实现这一目标?
答案 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());
}
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
}