将页面网址设为页面标题

时间:2013-05-01 10:05:33

标签: c# asp.net-mvc-4

将网页标题设为网址的最简单方法是什么?

目前我有:

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 
    }
);
...

我也希望用英语和本地语言,所以添加更多路线不会那么有意义......

1 个答案:

答案 0 :(得分:1)

如果需要从数据库中动态获取页面,请定义一条新路由以捕获所有请求。这条路线最后应该定义。

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);
    }
}

显然,所有页面都需要定义一个标题(或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() { /* ... */ }
}

我在一个中型项目上使用它并且它运行得很好。最大的好处是你总能知道路线的定义。

相关问题