2013-04-27 7 views
6

私はURLのようなstackoverflowを作成しようとしています。MVC 4はスラッグ型のURLを作成します

私は次の例で問題なく動作します。しかし、コントローラを取り外すと、エラーが発生します。

http://localhost:12719/Thread/Thread/500/slug-url-text 

最初のスレッドは2番目のアクションであることに注意してください。

URLからコントローラ名を除いて、上記のURLを次のように見えるようにするにはどうすればよいですか?デフォルトルートの定義の前に次のルートを置く

http://localhost:12719/Thread/500/slug-url-text 

マイルート

public class RouteConfig 
    { 
    public static void RegisterRoutes(RouteCollection routes) 
    { 
     routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); 

     routes.MapRoute("Default", // Route name 
      "{controller}/{action}/{id}/{ignoreThisBit}", 
      new 
      { 
       controller = "Home", 
       action = "Index", 
       id = "", 
       ignoreThisBit = "" 
      }); // Parameter defaults) 


    } 
} 

スレッド制御部

public class ThreadController : Controller 
{ 
    // 
    // GET: /Thread/ 

    public ActionResult Index() 
    { 

     string s = URLFriendly("slug-url-text"); 
     string url = "Thread/" + 500 + "/" + s; 
     return RedirectPermanent(url); 

    } 

    public ActionResult Thread(int id, string slug) 
    { 

     return View("Index"); 
    } 

}

答えて

13

は直接「スレッドの 'スレッド' アクションを呼び出します'' id 'と' slug 'パラメータを持つコントローラです。あなたは本当にそれはstackoverflowのようなもの、と誰かがID部分とないスラグの一部を入力すると仮定する場合

routes.MapRoute(
    name: "Thread", 
    url: "Thread/{id}/{slug}", 
    defaults: new { controller = "Thread", action = "Thread", slug = UrlParameter.Optional }, 
    constraints: new { id = @"\d+" } 
); 

はその後、

public ActionResult Thread(int id, string slug) 
{ 
    if(string.IsNullOrEmpty(slug)){ 
     slug = //Get the slug value from db with the given id 
     return RedirectToRoute("Thread", new {id = id, slug = slug}); 
    } 
    return View(); 
} 

は、このことができます願っています。

+0

string.IsNullOrWhiteSpaceをstring.IsNullOrEmptyに変更すると、文字列をよりよくチェックできます。 –

関連する問題