Asp.net mvc 4 MVC4创建slug类型url

Asp.net mvc 4 MVC4创建slug类型url,asp.net-mvc-4,url-rewriting,slug,Asp.net Mvc 4,Url Rewriting,Slug,我正在尝试创建一个类似stackoverflow的url 我认为下面的例子很好用。但是如果我移除控制器,它就会出错 http://localhost:12719/Thread/Thread/500/slug-url-text 注意,第一个线程是控制器,第二个线程是动作 如何将控制器名称从URL中排除,使上面的URL看起来如下所示 http://localhost:12719/Thread/500/slug-url-text 我的路线 public class RouteConfig

我正在尝试创建一个类似stackoverflow的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");
    }

}

将以下路由置于默认路由定义之前,将使用“id”和“slug”参数直接调用“Thread”控制器中的“Thread”操作

routes.MapRoute(
    name: "Thread",
    url: "Thread/{id}/{slug}",
    defaults: new { controller = "Thread", action = "Thread", slug = UrlParameter.Optional },
    constraints: new { id = @"\d+" }
);
如果你真的想让它像stackoverflow一样,假设有人进入id部分而不是slug部分

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

希望这有帮助。

将string.IsNullOrEmpty更改为string.IsNullOrWhiteSpace,以更好地检查字符串。