2

使页面标题成为 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 
    }
);
...

我也想用英语和当地语言,所以添加更多路线没有多大意义......

4

1 回答 1

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() { /* ... */ }
}

我在一个中型项目中使用它,它工作得很好。最大的胜利是你总是知道你的路线是在哪里定义的。

于 2013-05-01T10:08:35.553 回答