【问题标题】:ASP.NET MVC 4 Parameters Separated by Forward Slashes "/" not passing args properly由正斜杠“/”分隔的 ASP.NET MVC 4 参数未正确传递参数
【发布时间】:2016-10-04 02:40:27
【问题描述】:

我正在尝试遵循许多网站使用的约定,这些网站使用多个正斜杠传入参数,而不是使用 GET 模型。

也就是说,我希望使用如下 URL:

http://www.foo.bar/controller/action?arg1=a&arg2=b&arg3=c

以这种方式:

http://www.foo.bar/controller/action/a/b/c

我目前(大部分)正在使用以下方法:

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

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

        routes.MapRoute(
            name: "Sandbox",
            url: "Sandbox/{action}/{*args}",
            defaults: new { controller = "Sandbox", action = "Index", args = UrlParameter.Optional }

        );
    }

但是,如果我传入类似的东西

http://www.foo.bar/Sandbox/Index/a 

http://www.foo.bar/Sandbox/Index/a/

适当地调用控制器和操作:

public ActionResult Index(string args)
{
    return View();
}

但 args 为空。

但是,如果我传入以下内容:

http://www.foo.bar.com/Sandbox/Index/a/b

然后根据需要,args 是“a/b”。

我一直在搜索 SO 和网络的其他部分,但似乎找不到解决方案。

我是否缺少一些明显的东西来纠正这种行为?

我是否在寻找错误的术语?

注意:我能够通过使用 Windows 身份验证的全新 ASP.NET 应用程序重现此问题。全部完成:

  1. 在 VS 2015 中创建 ASP.NET 应用程序
  2. 选择 MVC
  3. 点击更改身份验证
  4. 选择 Windows 身份验证
  5. 将上面的 Map Route 添加到 RouteConfig.cs
  6. 创建 SandboxController.cs 并将 args 参数添加到 Index
  7. 创建 Index.cshtml 视图
  8. 使用http://localhost:55383/Sandbox/Index/a 重现问题
  9. 使用http://localhost:55383/Sandbox/Index/a/b 重现预期行为

非常感谢任何帮助。谢谢! 类似的问题,但对我没有帮助:URLs with slash in parameter?

【问题讨论】:

  • 显示你所有的路线和顺序(你也有默认路线吗?)
  • 是的。我添加了它。我现在感觉很愚蠢。我意识到 Default 是第一个被调用的。

标签: c# asp.net asp.net-mvc asp.net-mvc-4


【解决方案1】:

没关系……问题来了……

MapRoute 首先调用默认路由。 为了解决这个问题,我只是将默认地图路线与沙盒路线交换。

我希望这对某人有所帮助。

工作解决方案:

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

        routes.MapRoute(
            name: "Sandbox",
            url: "Sandbox/{action}/{*args}",
            defaults: new { controller = "Sandbox", action = "Index", args = UrlParameter.Optional }

        );

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


    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-29
    • 1970-01-01
    • 2021-10-23
    • 1970-01-01
    • 2011-03-23
    • 2014-05-03
    • 2022-01-25
    • 2014-11-24
    相关资源
    最近更新 更多