6

我正在尝试创建一个类似 url 的 stackoverflow。

我下面的例子工作正常。但是,如果我卸下控制器,则会出错。

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

}

4

1 回答 1

14

将以下路由放在默认路由定义之前将直接使用 '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();
}

希望这可以帮助。

于 2013-04-27T13:38:44.823 回答