MVC 4:自定义路线

rei*_*ard 2 asp.net-mvc-routing asp.net-mvc-4

ASP.NET MVC 4网站.

有一个名为"Locations"的数据库表,它只包含三个可能的位置(例如"CA","NY","AT")默认路由为:

http://server/Location/  --- list of Locations
http://server/Location/NY --- details of NY-Location
Run Code Online (Sandbox Code Playgroud)

如何在没有/ Location/ - 位的情况下创建自定义路由?(我发现它更好一点)

以便

http://server/NY - details of NY
http://server/AT - details of AT
.... etc...
Run Code Online (Sandbox Code Playgroud)

http://server/Location  --- list of Locations
Run Code Online (Sandbox Code Playgroud)

Ric*_*ard 7

解决方案是使用路径约束来执行自定义路由:(顺序很重要)

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 }
);
Run Code Online (Sandbox Code Playgroud)

与匹配的控制器:

public class LocationController : Controller
{
    //
    // GET: /Location/
    public ActionResult Index()
    {
        return View();
    }

    //
    // GET: /{city}
    public ActionResult Details(string city)
    {
        return View(model:city);
    }
}
Run Code Online (Sandbox Code Playgroud)

如果你只想允许NY,CA和AT你可以写你的路由约束,如:

constraints: new { city = @"NY|CA|AT" }
Run Code Online (Sandbox Code Playgroud)

(小写也适用).另一种更通用的解决方案是使用路由约束来实现自己的解决方案IRouteConstraint.SE 我以前的答案.