通过Url传多个参数方法

MVC3通过URL传值,一般情况下都会遇到【从客户端(&)中检测到有潜在危险的 Request.Path 值】的问题

这个问题的解决方法,我的其他博文已经有了说明,这里给出连接【从客户端(&)中检测到有潜在危险的 Request.Path 值】解决方法

 

方法一:

Url传参是通过Get的方式,一般我们都是通过一定规则的Url来传参。比如下面的URL。

http://localhost/contorller/action/?Params1=a&Params2=b

 注意:URL里面的“?”不能去掉哦,我曾经将URL路由和url参数混淆,就是上面的URL里面没有“?”,搞了2天时间才弄清楚问题出在哪里。大家可不要犯同样的错误哦。

我们可以在controller中通过绑定方法的方式来进行获取,代码如下:

public ActionResult Index(ExpModel model, string Params1 , string Params2)
{
            ViewBag.P1 = Params1 ;
            ViewBag.P2= Params2; 
            return View();
}

方法二:

修改MVC3中的路由规则

在Global.asax.cs中,修改路由规则

 routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            routes.MapRoute(
                "Default", // 路由名称
                "{controller}/{action}/{id}", // 带有参数的 URL
                new { controller = "Home", action = "Index", id = UrlParameter.Optional} // 参数默认值
            );

 

MapRoute方法在RouteCollectionExtensions里有6个重载版本!在这里我挑了一个参数最多的重载版本来进行介绍

public static Route MapRoute(
    this RouteCollection routes,
    string name,
    string url,
    Object defaults,
    Object constraints,
    string[] namespaces
)

 

name:路由在路由列表里的唯一名字(两次MapRoute时name不能重复)

url:路由匹配的url格式

defaults:路由url {占位符} 的默认值

constraints:url的 {占位符} 的约束

namespaces:这个是用于设置路由搜索的控制器命名空间!

 

比如,我们可以修改为下面的规则

 routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            routes.MapRoute(
                "Default", // 路由名称
                "{controller}/{action}/{uid}_{token}_{others}.html", // 带有参数的 URL
                new { controller = "Home", action = "Index", uid = UrlParameter.Optional, token = UrlParameter.Optional,others = UrlParameter.Optional} // 参数默认值
            );

 

如果访问的URL地址如:http://localhost/home/index/123_tokenvalue_othersvalue.html 时

controller="Home", action="Index", uid=123, token=tokenvalue, others=othersvalue

获取和上面的方法一样。

关于Route 的详细用法和说明,大家看MSDN 上的资料吧,这里给个连接:

ASP.NET Routing:http://msdn.microsoft.com/en-us/library/cc668201.aspx?cs-save-lang=1&cs-lang=csharp

 

 

posted @ 2014-05-06 11:41  天马3798  阅读(20505)  评论(0编辑  收藏  举报