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

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM