文件来定义在MVC3路线 [英] File to define route in MVC3

查看:94
本文介绍了文件来定义在MVC3路线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个文件:

<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对象结构,以图请求与PARAMS良好的作用。
对于URL我的网址不尊重任何结构规则是很重要的。

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?

推荐答案

您可以设置一个MVC项目完全是随意的路线,从任何特定的URL结构免费的。

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

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

如果您想让它显示你的XML文件,我会做简单的东西如:

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
}

XML文件本身当然可以嵌在某种方式的项目,这是给你的。

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

编辑:

对于参数的处理,你可以轻松地发送您想使用 routes.MapRoute(...)命令的参数。只需添加它们是这样的:

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
}

这篇关于文件来定义在MVC3路线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆