【问题标题】:Optional id for default action默认操作的可选 ID
【发布时间】:2014-11-15 17:06:14
【问题描述】:

我有一个只有这条路线的网站:

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

    routes.MapRoute("Default", "{controller}/{action}/{id}",
        new { controller = "Image", action = "Image", id = UrlParameter.Optional }
        );
}

这是控制器:

public class ImageController : Controller
{
    public ActionResult Image(int? id)
    {
        if (id == null)
        {
            // Do something
            return View(model);
        }
        else
        {
            // Do something else
            return View(model);
        }
    }
}

现在这是默认操作,因此我无需 ID 即可直接访问我的域来访问它。要调用 id,转到 /Image/Image/ID 就可以了。但是我想要的是在没有图像/图像(所以 /ID)的情况下调用它。现在不行了。

这是默认路由的限制还是有办法让它工作?

谢谢

【问题讨论】:

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


    【解决方案1】:

    为此网址创建一个特定的新路由:

    routes.MapRoute(
        name: "Image Details",
        url: "Image/{id}",
        defaults: new { controller = "Image", action = "Image" },
        constraints: new { id = @"\d+" });
    

    确保在此之前注册上述路线:

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

    否则它将不起作用,因为默认路由将优先。

    这里我要说明的是,如果 url 包含“/Image/1”,则执行 ImageController/Image 操作方法。

    public ActionResult Image(int id) { //..... // }

    约束意味着 {id} 参数必须是一个数字(基于正则表达式\d+),因此不需要可为 null 的 int,除非您确实需要可为 null 的 int,在这种情况下删除约束.

    【讨论】:

    • 并在现有的controller/action/id 路由之前注册这条路由!
    • 建议用这个更新你的答案:)
    • 感谢这让我找到了正确的方向。我最终使用了这条路线。 routes.MapRoute("图片详情", "{id}", new {controller = "Image", action = "Image"} );我从 Image/{id} 中删除了 Image/。也不需要约束。
    • @Fortitude 强烈推荐约束,甚至可能是必需的。否则,对 /Home 之类的请求最终将匹配新的仅图像路由,而不是匹配 controller=Home
    猜你喜欢
    • 2021-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-19
    • 1970-01-01
    • 1970-01-01
    • 2011-06-29
    • 2018-12-08
    相关资源
    最近更新 更多