2013-04-27 21 views
6

Próbuję utworzyć stackoverflow jak URL.MVC 4 tworzenie adresu url typu

Poniższy przykład działa poprawnie. Ale jeśli usunę kontroler, to spowoduje to błąd.

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

Uwaga pierwszy wątek to kontroler, drugi to akcja.

Jak mogę sprawić, aby powyższy adres URL wyglądał jak poniżej, wykluczając nazwę kontrolera z adresu URL?

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

Moi Trasy

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) 


    } 
} 

Controller Wątek

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

}

Odpowiedz

13

Umieszczanie następującą trasą przed definicją domyślna trasa będzie bezpośrednio wywołać 'wątek' działania w „wątek "kontroler z parametrem" identyfikator "i" karetką ".

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

Następnie, jeśli naprawdę chcesz, żeby być jak stackoverflow i przejąć ktoś wchodzi część id, a nie część ślimak,

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

nadzieję, że to pomaga.

+0

Zmień ciąg.IsNullOrEmpty na string.IsNullOrWhiteSpace dla lepszego sprawdzania ciągu. –

Powiązane problemy