【问题标题】:How to add a MapRoute like example.com/id如何添加像 example.com/id 这样的 MapRoute
【发布时间】:2012-12-17 21:31:52
【问题描述】:

我想创建一个 URL 缩短器网站。我提供的 URL 类似于 example.com/XXX 在哪里 XXX 是短网址的值。

我想在example.com 上拥有网站,网址是example.com/xxx。我想从 URL 中获取 xxx 并将用户重定向到数据库中的等效 URL。

如何实现?

【问题讨论】:

    标签: c# asp.net-mvc-3 asp.net-mvc-routing url-routing


    【解决方案1】:

    您在默认控制器操作中执行所需重定向的一种方式。在 asp.net mvc 中默认是 home/index。

    所以在索引操作中你应该有这样的代码

    public ActionResult Index(string id)
    {
          var url = Db.GetNeededUrl(id);
          return Redirect(url);
    }
    

    所以现在,如果用户输入这样的地址 site.com/NewYear,您将被重定向到您数据库中的等效 url。

    【讨论】:

      【解决方案2】:

      例如在您的 RouteConfig 中创建一个新路由:

       public class RouteConfig
          {
              public static void RegisterRoutes(RouteCollection routes)
              {
                  routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
      
                  routes.MapRoute("empty",
                                  "{id}",
                                  new {controller = "Home", action = "Index", id = UrlParameter.Optional}
                      );
      
                  routes.MapRoute(
                      name: "Default",
                      url: "{controller}/{action}/{id}",
                      defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
                  );
      
              }
          }
      

      然后只需使用索引中传递的 id 转到您的数据库

        public ActionResult Index(int id)
        {
              //Do Stuff with db
              return View();
        }
      

      asp.net mvc 文档here.

      【讨论】:

        猜你喜欢
        • 2017-10-28
        • 1970-01-01
        • 2013-03-24
        • 1970-01-01
        • 2020-11-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-11-17
        相关资源
        最近更新 更多