【问题标题】:.NET MVC 4 routing with same number of parameters具有相同数量参数的 .NET MVC 4 路由
【发布时间】:2016-03-22 18:29:17
【问题描述】:

我有一个名为 Admin 的控制器,它有两个操作: 帖子 - 这个接受一个名为 screen 的获取参数 editpost - 这个接收一个名为 id 的 get 参数

现在我想路由呼叫,例如: Admin/posts?screen=1 为 Admin/posts/1 和 Admin/editpost?id=3 为 Admin/editpost/3

这两个参数都是整数,因此向路线添加约束是无用的(根据我的尝试)。 我已经在我的 RouteConfig.cs 中尝试过,但它失败了:

        routes.MapRoute(
          name: "Post pagination",
          url: "Admin/{screen}",
          defaults: new { controller = "Admin", action = "Posts" }
      );

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

另一个问题是: 如何从 RouteConfig.cs 文件中获取控制器和操作名称,以便为分页制定通用路由规则?

【问题讨论】:

    标签: .net asp.net-mvc-4 model-view-controller razor routing


    【解决方案1】:

    您只需要一个标准重定向。这最好由 IIS 直接处理。但是,如果你想使用 MVC,你只需要添加如下内容:

    public ActionResult Posts(int id)
    {
        if (Request.QueryString["id"] != null)
        {
            return RedirectToActionPermanent("Posts", "Admin", new { id = id });
        }
    
        ...
    }
    

    虽然这不是很优雅,所以我仍然建议使用 IIS 中的 URL 重写模块来处理。

    【讨论】:

      猜你喜欢
      • 2017-05-27
      • 1970-01-01
      • 2016-01-22
      • 2019-10-26
      • 2018-01-07
      • 1970-01-01
      • 1970-01-01
      • 2015-07-26
      • 1970-01-01
      相关资源
      最近更新 更多