【问题标题】:MVC 4: Custom RouteMVC 4:自定义路由
【发布时间】:2012-09-20 18:10:30
【问题描述】:

ASP.NET MVC 4 网站。

有一个名为“Locations”的数据库表,其中仅包含三个可能的位置(例如“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

【问题讨论】:

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

标签: asp.net-mvc-4 asp.net-mvc-routing


【解决方案1】:

一种解决方案是使用路由约束进行自定义路由: (顺序很重要)

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,而不是使用路由约束。硒my previous answer

【讨论】:

    【解决方案2】:

    您需要在控制器内指定路由。查看本教程了解如何指定路由约束:

    http://www.asp.net/mvc/tutorials/controllers-and-routing/creating-a-route-constraint-cs

    您使用路由约束来限制匹配的浏览器请求 特定的路线。您可以使用正则表达式来指定 路线约束。

    也可以看看这个帖子:How to map a route for /News/5 to my news controller

    【讨论】:

      猜你喜欢
      • 2015-06-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多