【问题标题】:MVC4 routing issue. Not able to customize URLMVC4 路由问题。无法自定义网址
【发布时间】:2015-09-06 16:34:55
【问题描述】:

下面是我的 RouteConfig.cs。

我想创建一个这样的网址

http://localhost:22723/Home*Index

所以我有如下所示的 Routeconfig.cs。我删除了所有默认设置。

routes.MapRoute(
    name: "Default3",
    url: "{controller}*{action}*{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

当我像下面这样输入 URL 时,它不起作用。

http://localhost:22723/Home*Index

请说明上述 URL 不起作用的原因以及如何使其起作用,

这种 URL 在 MVC4 中是否可行。

【问题讨论】:

  • * 被认为是 url 中的安全问题,所以你不能使用它,可能必须有其他替代方法而不是 * 。 HPE this 帮助
  • 我尝试使用 localhost:22723/Home-Index ,但没有成功。 Routes.MapRoute( name: "Default3", url: "{controller}-{action}-{id}", 默认值: new { controller = "Home", action = "Index", id = UrlParameter.Optional } );
  • 为什么你想要一些其他字符而不是 / ? @Hemanta

标签: asp.net-mvc-4 asp.net-mvc-routing


【解决方案1】:

正如 J Santosh 指出的那样,可以在 URL 中使用 *,但您必须禁用请求验证才能使其正常工作(不推荐)。

如果您想使用其他字符(除了/),您需要以不同的方式构建您的路由方案,因为Route 类不知道如何使除/ 之外的任何其他文字字符可选。下面是一个使用 - 文字字符的示例,但在 URL 中有效的任何其他字符都将以相同的方式工作。

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        // This must be first to prevent the home page from
        // being generated as /Home-Index
        routes.MapRoute(
            name: "Home",
            url: "",
            defaults: new { controller = "Home", action = "Index" }
        );

        routes.MapRoute(
            name: "ThreePlaceholders",
            url: "{controller}-{action}-{id}"
        );

        routes.MapRoute(
            name: "TwoPlaceholders",
            url: "{controller}-{action}"
        );

        routes.MapRoute(
            name: "OnePlaceholder",
            url: "{controller}",
            defaults: new { action = "Index" }
        );
    }
}

诀窍是您需要制作一套完整的 URL 模式并使每个占位符 必需 以确保每个路由仅在一个特定情况下匹配。您可以通过不提供默认值来制作所需的占位符。

路由框架匹配从第一个注册路由到最后一个注册路由的 URL 模式,第一个匹配总是获胜。因此,在这种情况下,您需要多种模式来处理 URL 中的可选文字字符。

【讨论】:

    猜你喜欢
    • 2013-03-13
    • 1970-01-01
    • 2014-03-30
    • 1970-01-01
    • 1970-01-01
    • 2016-12-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多