2013-04-27 1 views
6

url과 같은 stackoverflow를 생성하려고합니다.MVC 4 슬러그 타입 URL 생성

다음 예제는 잘 동작합니다. 하지만 컨트롤러를 제거하면 오류가 발생합니다.

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

첫 번째 스레드는 두 번째 동작 인 컨트롤러입니다.

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 '매개 변수가 있습니다.

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

그런 다음 당신은 정말, 그것이 유래처럼, 누군가가 ID 부분이 아닌 슬러그 부분에 진입 가정이 도움이

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를 변경하십시오. –