【问题标题】:ASP.NET MVC 5 Url Rewriting to encompass all actions in controller?ASP.NET MVC 5 Url 重写以包含控制器中的所有操作?
【发布时间】:2015-03-20 14:37:03
【问题描述】:

我想知道是否可以在 Route.Config 文件中编写一个规则来包含单个控制器中的所有操作?我已经阅读了this article,但它比我高一点(我刚开始进行 url 重写和路由,术语不熟悉)。

我已设法将我的一项操作从 mydomain.co.za/Trainee/Action?id=123 更改为 mydomain.co.za/Trainee/Action/123,但我希望能够包含 Trainee 控制器中的所有操作,这样您就可以有一个规则来生成 Trainee/Action1/123 或 @ 987654325@这是我用的代码:

        routes.MapRoute(
            name: "ActionRewrite",
            url: "Trainee/Action/{id}",
            defaults: new { controller = "Trainee", action = "Action" }
        );

附带说明一下,是否也可以隐藏 URL 中的参数,这样无论用户在做什么,您都可以简单地拥有 mydomain.co.za/Action/?

【问题讨论】:

  • 我会将附注作为第二个问题发布

标签: c# asp.net asp.net-mvc url-rewriting routes


【解决方案1】:

试试这个:

routes.MapRoute(
            name: "ActionRewrite",
            url: "Trainee/{action}/{id}",
            defaults: new { controller = "Trainee", action = {action} }
        );
  • 请记住,您可以使用通配符匹配您的网址。

  • 如果您愿意,可以指定 {id} 参数保持可选,这意味着它也将匹配未指定参数的操作。

【讨论】:

  • 这似乎成功了!我从来不知道您可以将您的操作指定为“参数”。谢谢。
  • @barnacle.m 是的,它非常灵活。对于真正的自定义路由,您可以查看实现自定义控制器工厂,您可以在其中访问路由数据集合。身边的例子很多。很高兴它有效
【解决方案2】:

试试这个.. Url Rewiring in using custom id and name . 在应用启动路由配置中添加。

公共类 RouteConfig { 公共静态无效注册路由(RouteCollection 路由) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); 路线.MapMvcAttributeRoutes(); routes.MapRoute( name: "contactus", url: "contactus", defaults: new { Controller = "Cms", action = "Index", id = (int)Common.CMSContactUs }, namespaces: new[] { "QZero.Controllers" } ); routes.MapRoute( name: "aboutus", url: "aboutus", defaults: new { Controller = "Cms", action = "Index", id = (int)Common.CMSAboutUs }, namespaces: new[] { "QZero.Controllers" } ); routes.MapRoute( name: "useragreement", url: "useragreement", defaults: new { Controller = "Cms", action = "Index", id = (int)Common.CMSUserAgreement }, namespaces: new[] { "QZero.Controllers" } ); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }, namespaces: new[] { "QZero.Controllers" } ); } }

【讨论】:

    猜你喜欢
    • 2018-10-14
    • 1970-01-01
    • 2010-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-15
    • 2018-01-22
    相关资源
    最近更新 更多