【问题标题】:how to shorten controller name, and action name in output URL in MVC 4?如何在 MVC 4 的输出 URL 中缩短控制器名称和动作名称?
【发布时间】:2013-12-27 13:08:45
【问题描述】:

我正在编写一个 MVC 4 应用程序,它具有控制器和许多冗长的操作名称,它们创建了一个不容易记住的冗长 URL。

知道如何在 MVC 4 中实现短 URL(最好不影响路由)吗?可能正在使用自定义属性?

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-4 url-rewriting url-shortener


    【解决方案1】:

    实际上,您可以在 RouteConfig.cs 中指定您的路线。这是我的应用程序中的代码:

        routes.MapRoute("SignUp", "signup", new { controller = "SignUp", action = "Index" });
        routes.MapRoute("SignOut", "signout", new { controller = "Login", action = "SignOut" });
        routes.MapRoute("Login", "login", new { controller = "Login", action = "Login" });
    

    这里的第二个参数(注册、注销、登录)是短网址。如果你想要更多的东西,你可以像这样指定你的路线:

        routes.MapRoute("SetNewPassword", "set-new-password/{userId}/{passwordResetKey}", new { controller = "SetNewPassword", action = "Index" });
    

    这里的网址类似于 /set-new-password/123/blabla

    新路由不会影响默认路由。只需确保最后有这个默认行:

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    

    顺便说一句,您可以使用来自 Phil Haack 的方便的route debugger。它非常易于设置和使用(您只需在 Global.asax.cs 中注释/取消注释一行)。它绝对是每个 Asp.Net MVC 开发人员必备的工具。

    【讨论】:

      【解决方案2】:

      可能是一个“笼统”的路由会帮助你。

      您可以设置一个包罗万象的路由,将所有 /something 请求定向到特定的操作和控制器,例如:

      routes.MapRoute( “短网址”, “{姓名}”, 新 {controller = "ShortUrl", action = "Index", name = UrlParameter.Optional} ); (取决于你的路由的其余部分是如何设置的,你可能不想完全这样做,因为它可能会给你带来一些严重的路由问题——但为了简单起见,这里可行)

      然后根据指定的值将您的操作重定向到所需的 URL:

      public class ShortUrlController : Controller
      {
        //
        // GET: /ShortUrl/
      
        public ActionResult Index(string name)
        {
          var urls = new Dictionary<string, string>();
          urls.Add("disney", "http://..your lengthy url");
          urls.Add("scuba", "http://another..lengthy url");
          return Redirect(urls[name]);
        }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-06-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-12-31
        相关资源
        最近更新 更多