[英]Advanced MVC.NET Routing
我目前正在尝试以以下方式进行路由。
到目前为止,我有以下代码:
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.