我正在尝试创建像url一样的stackoverflow.
我以下示例工作正常.但是,如果我删除控制器,那么它会出错.
http://localhost:12719/Thread/Thread/500/slug-url-text
注意第一个Thread是控制器,第二个是动作.
如何使上面的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(); }
希望这可以帮助.