簡體   English   中英

先進的MVC.NET路由

[英]Advanced MVC.NET Routing

我目前正在嘗試以以下方式進行路由。

  • /路由到Home控制器,查看操作,將“ home”作為id
  • / somePageId路由到Home控制器,查看操作,將“ 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中可以嗎? 如果是這樣,我將如何處理?

嘗試從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路由。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM