一种解决方案是使用路由约束进行自定义路由:(顺序很重要)
routes.MapRoute(
name: "City",
url: "{city}",
constraints: new { city = @"\w{2}" },
defaults: new { controller = "Location", action = "Details", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
使用匹配的控制器:
public class LocationController : Controller
{
//
// GET: /Location/
public ActionResult Index()
{
return View();
}
//
// GET: /{city}
public ActionResult Details(string city)
{
return View(model:city);
}
}
如果您只想允许 NY、CA 和 AT,您可以编写路由约束,例如:
constraints: new { city = @"NY|CA|AT" }
(小写也可以)。另一个更通用的解决方案而不是使用路由约束是实现你自己的IRouteConstraint. 看我之前的回答。