【问题标题】:Attirbute based routing for ASP.Net controllerASP.Net 控制器的基于属性的路由
【发布时间】:2016-05-24 06:45:37
【问题描述】:

我知道基于属性的路由适用于操作级别,但我可以在控制器级别使用相同的路由吗?

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

【问题讨论】:

  • 您能否给出一个包含C1C2 的示例网址,这些网址将映射到C1Controller。这样可以建议适当的路线模板来满足您的要求。

标签: asp.net asp.net-mvc


【解决方案1】:

从帖子中得到答案

“最正确的方法是创建一个继承 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

希望这会有所帮助!

【讨论】:

    【解决方案2】:

    试试这个

    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
    }
    

    【讨论】:

    • OP 正在询问 路由。此操作过滤器执行重定向。它与问题无关。
    • 它将被重定向到另一个页面
    • 是的,它会向浏览器发送一个 302 HTTP 响应,告诉它在服务器上查找一个新位置。路由通过直接访问服务器端的action方法避免了跨网络的往返。
    • 为此我们需要使用[Route("ActionName")]这个属性
    猜你喜欢
    • 2020-10-03
    • 2019-10-03
    • 1970-01-01
    • 2021-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-14
    • 2021-10-30
    相关资源
    最近更新 更多