【问题标题】:Nice URLs based on multiple parameters基于多个参数的漂亮 URL
【发布时间】:2011-03-12 17:30:28
【问题描述】:

很清楚在您的网站中使用漂亮的 url 有什么好处。

让我通过一个例子来澄清我在问什么。请注意,此处的实体不能通过名称唯一标识。

假设用户希望查看在您的站点上注册且在特定位置可用的所有广播电台。这是通过访问 url 来完成的: http://example.com/radios/1234/radio-paris-eiffel-tower

  • 1234 - 在这种情况下是位置的唯一 ID
  • radio-paris-eiffel-tower - 只是让网址更美观的附加信息。

如果用户想要查看可以访问特定广播电台的所有位置,他们可以使用: http://example.com/locations/abcd/radio-xyz

  • abcd - 此处标识收音机

现在的问题是:在特定位置(如名称、频率等)访问特定广播电台的广播电台详细信息的好网址是什么?

http://example.com/radio/1234/radio-paris-eiffel-tower/abcd/radio-xyz 要么 http://example.com/radio/details?radioid=1234&locationid=abcd/radio-xyz-at-paris-eiffel-tower

您有什么建议吗?能否请您也给我一个示例,说明如何为您建议的 url 编码路线?

非常感谢。

ps: 实际上考虑上面的网址,而不是 http://example.com/radios/1234/radio-paris-eiffel-tower

会更好 http://example.com/1234/radio-paris-eiffel-tower/radios/

wdyt?

如何将这样的路由映射到 RadiosController.ListByLocation(int locationId)?

【问题讨论】:

    标签: asp.net-mvc url-routing friendly-url


    【解决方案1】:

    这是使用自定义路线的建议。我已经在 Global.asax.cs 文件中进行了设置:

    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    
        routes.MapRoute(
            "Radio and Frequency Route", // Route name
            "radio/details/{radioId}/{locationId}/{someUnusedName}", // URL with parameters
            new
            {
                controller = "Some",
                action = "SomeAction",
                radioId = string.Empty,
                locationId = string.Empty
            }
        );
    
        routes.MapRoute(
            "Default", // Route name
            "{controller}/{action}/{id}", // URL with parameters
            new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
        );
    
    }
    

    控制器非常简单:

    public class SomeController : Controller
    {
        public ActionResult SomeAction(string radioId, string locationId)
        {
            ViewData["radioId"] = radioId;
            ViewData["locationId"] = locationId;
    
            return View();
        }
    
    }
    

    它会响应前缀为 /radio/details 的 URL:

    http://localhost:51149/radio/details/123/456/moo
    http://localhost:51149/radio/details/abc/xyz/foo
    

    现在您可以构建适合您需要的任何类型的友好 URL。也许您想将 /radio/details 前缀更改为其他内容?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-01-15
      • 2011-01-22
      • 2017-04-16
      • 2016-02-17
      • 1970-01-01
      • 1970-01-01
      • 2021-03-15
      相关资源
      最近更新 更多