我正在尝试创建一个类似URL的stackoverflow。
我下面的示例工作正常。但是,如果我卸下 Controller ,则会出错。
http://localhost:12719/Thread/Thread/500/slug-url-text
注意,第一个线程是 Controller ,第二个是 Action 。
我如何才能使上面的URL看起来像以下内容,但从URL中排除 Controller 名称?
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 )
}
}
线程 Controller
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' Controller 中调用'Thread'操作。
routes.MapRoute(
name: "Thread",
url: "Thread/{id}/{slug}",
defaults: new { controller = "Thread", action = "Thread", slug = UrlParameter.Optional },
constraints: new { id = @"\d+" }
);
然后,如果您真的希望它像stackoverflow,并假设有人输入了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();
}
希望这可以帮助。
关于asp.net-mvc-4 - MVC 4创建子弹类型的URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16248732/