4创建蛞蝓种类网址

4创建蛞蝓种类网址

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

问题描述

我试图创建一个类似URL的计算器。

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''主题'控制和'塞'参数'主题'行动。

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

那么,如果你真的想成为像计算器,并假设有人进入ID一部分,而不是塞的一部分,

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创建蛞蝓种类网址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 02:43