MVC 4 创建 slug 类型 url [英] MVC 4 creating slug type url

查看:20
本文介绍了MVC 4 创建 slug 类型 url的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

i am trying to create a stackoverflow like url.

我下面的例子工作正常.但是如果我移除控制器,它就会出错.

I the following example works fine. But if i remove the controller then it errors out.

http://localhost:12719/Thread/Thread/500/slug-url-text

注意第一个线程是控制器,第二个是动作.

Note the first Thread is the controller the second is the action.

如何使上面的 URL 看起来像下面这样,从 URL 中排除控制器名称?

How can i make the above URL look like the following excluding the controller name from the 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' 操作.

Placing the following route before the default route definition will directly call the 'Thread' action in 'Thread' controller with the 'id' and 'slug' parameter.

routes.MapRoute(
    name: "Thread",
    url: "Thread/{id}/{slug}",
    defaults: new { controller = "Thread", action = "Thread", slug = UrlParameter.Optional },
    constraints: new { id = @"d+" }
);

然后,如果您真的希望它像 stackoverflow 一样,并假设有人输入了 id 部分而不是 slug 部分,

Then if you really want it to be like stackoverflow, and assume someone enters the id part and not the slug part,

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

希望这会有所帮助.

这篇关于MVC 4 创建 slug 类型 url的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆