2012-09-20 163 views
2

ASP.NET MVC 4网站。MVC 4:自定义路线

得到了一个名为“位置”数据库表,其中包含只有三个可能的位置(例如,“CA”,“NY”,“AT”) 默认路由是:

http://server/Location/ --- list of Locations 
http://server/Location/NY --- details of NY-Location 

如何我可以在没有/ Location/- 位的情况下创建自定义路线吗? (我觉得这一点更漂亮)

这样

http://server/NY - details of NY 
http://server/AT - details of AT 
.... etc... 

http://server/Location --- list of Locations 
+0

将其设置在控制器中?在控制器内部,您必须指定路线,然后指定它附带的功能,对不对?所以将路由设置为'server/{city}' – Steven

回答

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 } 
); 

与匹配的控制器:

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。 Se my previous answer