ASP.NET MVC 自定义路由中几个需要注意的小细节
本文主要記錄在ASP.NET MVC自定義路由時(shí),一個(gè)需要注意的參數(shù)設(shè)置小細(xì)節(jié)。 舉例來(lái)說(shuō),就是在訪(fǎng)問(wèn) http://localhost/Home/About/arg1/arg2/arg3 這樣的自定義格式的路由時(shí),有幾點(diǎn)要注意:
1、arg1/arg2/arg3 的部分應(yīng)該在 routes.MapRoute 中設(shè)置默認(rèn)值UrlParameter.Optional,才允許同時(shí)訪(fǎng)問(wèn)只傳部分值比如 只傳 arg1,或者 arg1/arg2 這樣的路徑
2、在設(shè)置默認(rèn)值的情況下,如果出現(xiàn) http://localhost/Home/About/arg1//arg3 這樣的鏈接,到底arg2是否有傳值進(jìn)來(lái)?
3、對(duì)于http://localhost/Home/ShowAbout/11?arg1=1&arg2=2&arg3=333 這樣的鏈接,到底 arg1取的是1還是11?
以下為路由配置的代碼,并沒(méi)有為test1和test2設(shè)置參數(shù)默認(rèn)值
public class RouteConfig{public static void RegisterRoutes(RouteCollection routes){routes.IgnoreRoute("{resource}.axd/{*pathInfo}");routes.MapRoute(name: "ShowAbout",url: "Home/ShowAbout/{arg1}/{arg2}/{arg3}",defaults: new { controller = "Home", action = "ShowAbout", arg1 = UrlParameter.Optional});routes.MapRoute(name: "Default",url: "{controller}/{action}/{id}",defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional });}}?以下為HomeController中的相關(guān)代碼
public JsonResult ShowAbout(string arg1, string arg2, string arg3) {return Json(arg1 + "," + arg2 + "," + arg3, JsonRequestBehavior.AllowGet);}當(dāng)我們?cè)L問(wèn)鏈接 http://localhost/Home/ShowAbout/arg1/arg2/arg3 時(shí),會(huì)出現(xiàn)如下結(jié)果:
"arg1,arg2,arg3"但如果少了一個(gè)參數(shù),比如訪(fǎng)問(wèn) http://localhost/Home/ShowAbout/arg1/arg2 ,則會(huì)出現(xiàn) 404 的錯(cuò)誤
這種情況下,需要在RouteConfig中配置默認(rèn)值
routes.MapRoute(name: "ShowAbout",url: "Home/ShowAbout/{arg1}/{arg2}/{arg3}",defaults: new {controller = "Home",action = "ShowAbout",arg1 = UrlParameter.Optional,arg2 = UrlParameter.Optional,arg3 = UrlParameter.Optional});UrlParameter.Optional解決了不管參數(shù)是值類(lèi)型還是引用類(lèi)型,在未傳對(duì)應(yīng)參數(shù)的情況下,都會(huì)提供一個(gè)默認(rèn)值(如0或者null)
這個(gè)時(shí)候再訪(fǎng)問(wèn)鏈接 http://localhost/Home/ShowAbout/arg1/arg2? ,則會(huì)出現(xiàn)如下結(jié)果,而不會(huì)報(bào)錯(cuò)
"arg1,arg2,"當(dāng)我們傳入http://localhost/Home/ShowAbout/arg1//arg3,也就是故意不傳arg2的值的時(shí)候,會(huì)發(fā)現(xiàn)結(jié)果是
"arg1,arg3,"也就是arg3實(shí)際傳給了參數(shù)arg2的位置,兩個(gè)//還是三個(gè)///都會(huì)被忽略成一個(gè) /
當(dāng)我們?cè)L問(wèn) http://localhost/Home/ShowAbout/11?arg1=1&arg2=2&arg3=333 這樣的鏈接時(shí)候,發(fā)現(xiàn)結(jié)果是:
"11,2,333"即當(dāng)Action方法的參數(shù)是Binding類(lèi)型的時(shí)候, MVC框架會(huì)將路由參數(shù)優(yōu)先于查詢(xún)字符串值
?
轉(zhuǎn)載于:https://www.cnblogs.com/hxhbluestar/p/3537778.html
與50位技術(shù)專(zhuān)家面對(duì)面20年技術(shù)見(jiàn)證,附贈(zèng)技術(shù)全景圖總結(jié)
以上是生活随笔為你收集整理的ASP.NET MVC 自定义路由中几个需要注意的小细节的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 干货!表达式树解析框架(3)
- 下一篇: 如何分析apache日志[access_