我正在尝试创建一个通用路由来处理 slug,但我总是遇到错误
我的想法是,我在 url 中得到一个友好的 www.site.com/{slug} 而不是 www.site.com/controller/action
例如www.site.com/Home/Open 将改为 www.site.com/open-your-company
错误
server error in '/' application The Resource cannot be found
在我的 Global.asax 我有
public static void RegisterRoutes(RouteCollection routes)
{
//routes.Clear();
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute("DefaultSlug", "{slug}", new { controller = "Home", action = "Open", slug = "" });
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new
{
area = "",
controller = "Home",
action = "Index",
id = UrlParameter.Optional,
slug = ""
}
);
}
在我的一个 cshtml
中,我有以下链接(即使它被评论,仍然有同样的错误)。
@Html.ActionLink("Open your company", "DefaultSlug", new { controller = "Home", action = "Open", slug = "open-your-company" })
编辑:家庭 Controller
public ActionResult Open() {
return View(new HomeModel());
}
最佳答案
在 Global.asax 中你的 slug
不能为空,如果为空,url 将不会转到默认路由
public static void RegisterRoutes(RouteCollection routes)
{
//routes.Clear();
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "DefaultSlug",
url: "{slug}",
defaults: new { controller = "Home", action = "Open" },
constraints: new{ slug=".+"});
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new
{
area = "",
controller = "Home",
action = "Index",
id = UrlParameter.Optional
}
);
}
并更新 HomeController
public ActionResult Open(string slug) {
HomeModel model = contentRepository.GetBySlug(slug);
return View(model);
}
测试路线链接...
@Html.RouteLink("Open your company", routeName: "DefaultSlug", routeValues: new { controller = "Home", action = "Open", slug = "open-your-company" })
和操作链接...
@Html.ActionLink("Open your company", "Open", routeValues: new { controller = "Home", action = "Open", slug = "open-your-company" })
两者都产生...
http://localhost:35979/open-your-company
关于使用 Slug 的 C# Mvc 通用路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37193072/