3

我有这个文件:

<fru>
 <url action="product" controler="Home" params="{id=123}" >this_is_the_an_arbitrary_url_of_a_product.html</url>
 <url action="customer" controler="Home" params="{id=445}" >this_is_the_an_arbitrary_url_of_a_customer.html</url>
... other urls ...
</fru>

我正在寻找将此文件或此对象结构与 MVCHandler 绑定,以便将请求映射到具有参数的良好操作。对于 url 我来说,重要的是 url 不遵守任何结构规则。

有没有办法做到这一点?

4

1 回答 1

2

您可以为 MVC 项目设置完全任意的路由,不受任何特定 URL 结构的影响。

在 Global.asax.cs 中:

public static void RegisterRoutes(RouteCollection routes)
{
    routes.MapRoute(
        "",
        "superweirdurlwithnostructure.whatever",
        new { controller = "Home", action = "Products", id = 500 }
    );
}

确保在映射正常路线之前执行此操作。这些特定的需要先行,否则默认路由条目将阻止请求通过。

如果你想基于你展示的 XML 文件,我会做一些简单的事情:

XDocument routes = XDocument.Load("path/to/route-file.xml");
foreach (var route in routes.Descendants("url"))
{
    //pull out info from each url entry and run the routes.MapRoute(...) command
}

XML 文件本身当然可以以某种方式嵌入到项目中,这取决于您。

编辑:

至于参数的处理,您可以使用routes.MapRoute(...)命令轻松发送您想要的任何参数。只需像这样添加它们:

routes.MapRoute(
    "",
    "my/route/test",
    new { controller = "Home", action = "Index",
          id = "500", value = "hello world" } // <- you can add anything you want
);

然后在动作中,您只需这样做:

//note that the argument names match the parameters you listed in the route:
public ActionResult Index(int id, string value)
{
    //do stuff
}
于 2012-10-30T09:32:11.770 回答