asp.net-mvc-4 - MVC 4创建子弹类型的URL

标签 asp.net-mvc-4 url-rewriting slug

我正在尝试创建一个类似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/

相关文章:

apache - 如何将 htaccess 重写规则应用于包含换行符 (%0A) 的 URL?

php - Codeigniter - SEO 友好的 URL 结构(Slug 实现)

python-3.x - Django forms.ModelForm slugfield db_index=True

c# - ASP.NET Web API 从模型生成所有参数 - 帮助页面

asp.net-mvc-4 - 子文件夹中的 Controller ASP.Net MVC 4

asp.net-mvc-4 - 为没有关联 Controller 的 cshtml 文件启用缓存

c# - 如何先创建 EntityFramework 代码的可视化模型

apache - 通过子域将 Apache 代理到 Tomcat,使用 mod_jk,将路径隐藏在 url 中

java - 我需要在 PrettyFaces 中为此制作自定义正则表达式模式吗

php - Laravel 从数据库中获取 Slug