File to define route in MVC3

十年热恋 提交于 2019-12-10 09:43:49

问题


I have this file :

<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>

I'm looking for binding this file or this object structure with the MVCHandler, in order to map the request to the good action with the params. It's important for the url me that the urls doesn't respect any structure rules.

Is there a way to do this?


回答1:


You can set up completely arbitrary routes for an MVC project, free from any specific URL structure.

In Global.asax.cs:

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

Make sure you do this before mapping the normal routes. These specific ones need to go first, or the default route entries will stop the requests from coming through.

If you want to base it on the XML file you showed, I'd do something as simple as:

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
}

The XML file itself could of course be embedded in the project in some way, that's up to you.

Edit:

As for the handling of parameters, you can easily send any parameters you want using the routes.MapRoute(...) command. Just add them like this:

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

Then in the action, you simply do it like this:

//note that the argument names match the parameters you listed in the route:
public ActionResult Index(int id, string value)
{
    //do stuff
}


来源:https://stackoverflow.com/questions/13135633/file-to-define-route-in-mvc3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!