c# - 将页面 url 设为页面标题

标签 c# asp.net-mvc-4

将页面标题设为 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/

相关文章:

c# - 为特定 Controller 操作选择自定义输出缓存提供程序

c# - 如何绑定(bind)到 CheckedListBox.SelectedItems.Count

c# - 如何使用 LEADTOOLS 编辑 DICOM 文件的患者数据

c# - 你调用的对象是空的

asp.net-mvc - Elmah.MVC 在 IIS Express 下工作,但不能在 IIS 7.5 下工作

javascript - 调试在 javaScript 代码中不起作用,在 asp .net MVC4 应用程序中

c# - Identity Owin 是否需要延迟加载?

c# - 如何从 Xelement 中获取根元素

mysql - Asp.NET MVC 如何在数据表中快速显示大量数据

wcf - 如何在一处声明 MVC 模型和 WCF DataContract?