【问题标题】:Default mvc 5 route with guid id带有 guid id 的默认 mvc 5 路由
【发布时间】:2014-02-26 08:50:17
【问题描述】:

我正在尝试设置一个 mvc 5 属性路由,以便

https://localhost/19a6de7e-ee19-43f5-a9c9-8bbdc8dcfc5e

路由到 /home/index 初始化 id 参数,我似乎无法完全正确。

我添加了 routes.MapMvcAttributeRoutes();在默认映射路由之后到我的注册路由

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

我已经尝试了很多方法,但除非完全定义路线,否则似乎无法让它工作。

有什么建议吗?

public class HomeController : Controller
{
    [Route("{id?}")]
    public ActionResult Index(Guid? id)
    {
        ViewBag.Message = id;
        return View();
    }
}

【问题讨论】:

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


    【解决方案1】:

    现在添加了一个内置的 GuidRouteConstraint(),它比使用 RegEx 更可取。

    Differentiate Guid and string Parameters in MVC 3

    【讨论】:

      【解决方案2】:

      @chrisp_68,您需要在默认路由之前放置一个自定义路由:

      routes.MapRoute(
          name: "Just ID",
          url: "{id}",
          defaults: new { controller = "Home", action = "Index" }
      );
      

      然后,你需要创建一个以id为参数的动作:

      public ActionResult IndexID(string id) {
          ...
      }
      

      您可能会考虑的另一件事是将 id 的值限制为 guid 模式:

          constraints: new { id = @"[a-f0-9-]+" }
      

      (或者你需要的任何模式)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-12-15
        • 2016-04-25
        • 1970-01-01
        • 2010-11-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多