将页面url设置为页面标题
本文关键字:标题 url 设置 | 更新日期: 2023-09-27 18:11:50
用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
我想在每个页面上添加一个route
(只有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 = ""
}
)
然后在控制器中:
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);
}
}
显然,所有页面都需要定义一个标题(或通常所说的段号)。
如果每个页面都有静态操作,可以使用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() { /* ... */ }
}
我在一个中等规模的项目中使用它,它工作得很好。最大的好处是你总是知道你的路由在哪里定义。