You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET MVC5多城市路由配置问题:按城市/控制器/Action路由

ASP.NET MVC5 多城市路由实现方案

1. 调整路由配置(RouteConfig.cs)

给带城市前缀的路由设置更高优先级,同时添加路由约束避免和现有控制器名冲突,再保留原有默认路由兼容旧场景:

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        // 多城市路由,优先级高于默认路由
        routes.MapRoute(
            name: "CityRoute",
            url: "{city}/{controller}/{action}/{id}",
            defaults: new { action = "Index", id = UrlParameter.Optional },
            constraints: new { city = @"^[a-zA-Z-]+$" } // 约束城市名格式,可按需调整
        );

        // 原有默认路由,兼容无城市前缀的访问
        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }
}

2. 更新Restaurant控制器的Index方法

需要接收city参数,并根据城市过滤餐厅数据(假设你的Restaurant模型有City属性):

public ActionResult Index(string city, int? RestaurantId)
{
    var restaurantsQuery = db.Restaurants.AsQueryable();

    // 传入城市参数时,过滤对应城市的餐厅
    if (!string.IsNullOrWhiteSpace(city))
    {
        restaurantsQuery = restaurantsQuery.Where(r => r.City.Equals(city, StringComparison.OrdinalIgnoreCase));
    }

    var sortedRestaurants = restaurantsQuery.OrderBy(r => r.RestaurantName).ToList();
    ViewBag.Restaurants = new SelectList(sortedRestaurants, "RestaurantID", "RestaurantName");

    return View(sortedRestaurants);
}

3. 路由匹配说明

  • 访问London/Restaurant/Index时,会匹配CityRoute,city参数被传递到Index方法,返回伦敦的餐厅列表。
  • 访问原格式Restaurant/Index时,会匹配Default路由,city参数为null,返回所有餐厅(兼容原有单城市场景)。

关键注意点

  • 若Restaurant模型没有City字段,需先添加该属性并更新数据库结构。
  • 路由约束^[a-zA-Z-]+$可根据实际城市命名规则调整,比如允许数字或其他字符,核心是避免和现有控制器名称冲突。
  • 如果不需要兼容旧的单城市路由,可以删除Default路由,仅保留CityRoute。

内容的提问来源于stack exchange,提问作者Daark_Archer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 02:12:15