将页面标题设为 url 的最简单方法是什么?
目前我有:
http://localhost:53379/Home/Where
http://localhost:53379/Home/About
http://localhost:53379/Home/What
想要拥有
http://localhost:53379/where-to-buy
http://localhost:53379/about-us
http://localhost:53379/what-are-we
我考虑过为每个页面添加一个路由
(只有 9 个页面),但我想知道是否有更好的东西,例如对于大型网站。
routes.MapRoute(
name: "Default",
url: "where-to-buy",
defaults: new {
controller = "Home",
action = "Where",
id = UrlParameter.Optional
}
);
...
而且我也希望它有英语和本地语言版本,所以添加更多路线没有多大意义...
最佳答案
如果您需要从数据库中动态获取页面,请定义一个新路由来捕获所有请求。这个路由应该最后定义。
routes.MapRoute(
name: "Dynamic",
url: "{title}",
defaults: new {
controller = "Home",
action = "Dynamic",
title = ""
}
)
然后在你的 Controller 中:
public class HomeController {
public ActionResult Dynamic(string title) {
// All requests not matching an existing url will land here.
var page = _database.GetPageByTitle(title);
return View(page);
}
}
显然,所有页面都需要定义一个标题(或通常所说的 slug)。
如果每个页面都有静态操作,则可以使用 AttributeRouting .它将允许您使用属性为每个操作指定路由:
public class SampleController : Controller
{
[GET("Sample")]
public ActionResult Index() { /* ... */ }
[POST("Sample")]
public ActionResult Create() { /* ... */ }
[PUT("Sample/{id}")]
public ActionResult Update(int id) { /* ... */ }
[DELETE("Sample/{id}")]
public string Destroy(int id) { /* ... */ }
[Route("Sample/Any-Method-Will-Do")]
public string Wildman() { /* ... */ }
}
我在一个中型项目中使用它,并且效果很好。最大的好处是您始终知道路线的定义位置。
关于c# - 将页面 url 设为页面标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16316190/