高级MVC.NET路由

本文关键字:路由 NET MVC 高级 | 更新日期: 2023-09-27 18:20:34

我目前正在尝试以以下方式进行路由。

  • /路由到主控制器,查看操作,"主"作为id
  • /somePageId路由到主控制器,查看操作,"somePageId"作为id
  • /视频路由到视频控制器,索引操作
  • /Videos/someVideoName路由到视频控制器,id参数为"someVideoName"的视频操作
  • /新闻到新闻控制器的路线,索引操作
  • /News/someNewsId路由到新闻控制器,查看操作,"someNewsId"作为id

到目前为止,我有以下代码:

routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
    namespaces: new[] { "TheSportsOfficeWeb.Controllers" }
);
routes.MapRoute(
    name: "NewsIndex",
    url: "News",
    defaults: new { controller = "News", action = "Index" },
    namespaces: new[] { "TheSportsOfficeWeb.Controllers" }
);
routes.MapRoute(
    name: "NewsView",
    url: "News/{id}",
    defaults: new { controller = "News", action = "_", id = UrlParameter.Optional },
    namespaces: new[] { "TheSportsOfficeWeb.Controllers" }
);
routes.MapRoute(
    name: "PageShortCut",
    url: "{id}",
    defaults: new { controller = "Home", action = "_", id = UrlParameter.Optional },
    namespaces: new[] { "TheSportsOfficeWeb.Controllers" }
);

如果我去/Home/_/About,我可以查看页面,如果我去/About,我只得到404。

这在mvc.net中可能吗?如果是的话,我该怎么办?

高级MVC.NET路由

尝试从PageShortCut路由中删除UrlParameter.Optional。您可能还需要重新安排路线。

这对我有效(作为最后两条路线):

routes.MapRoute(
    name: "PageShortCut",
    url: "{id}",
    defaults: new { controller = "Home", action = "_" },
    namespaces: new[] { "TheSportsOfficeWeb.Controllers" }
);
routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
    namespaces: new[] { "TheSportsOfficeWeb.Controllers" }
);

我的控制器:

public class HomeController : Controller {
    public string Index(string id) {
        return "Index " + id;
    }
    public string _(string id) {
        return id;
    }
}

当您告诉路由引擎id对于路由不是可选的时,它不会使用该路由,除非存在id。这意味着对于没有任何参数的URL,引擎将采用Default路由。