File to define route in MVC3

做~自己de王妃 提交于 2019-12-06 02:02:52

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