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

各ページに a を追加することも考えました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);
    }
}

明らかに、すべてのページにタイトル (または一般的に呼ばれるスラッグ) を定義する必要があります。


ページごとに静的アクションがある場合は、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 に答える