日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > asp.net >内容正文

asp.net

ASP.NET MVC 自定义路由中几个需要注意的小细节

發布時間:2025/3/20 asp.net 29 豆豆
生活随笔 收集整理的這篇文章主要介紹了 ASP.NET MVC 自定义路由中几个需要注意的小细节 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

本文主要記錄在ASP.NET MVC自定義路由時,一個需要注意的參數設置小細節。 舉例來說,就是在訪問 http://localhost/Home/About/arg1/arg2/arg3 這樣的自定義格式的路由時,有幾點要注意:

1、arg1/arg2/arg3 的部分應該在 routes.MapRoute 中設置默認值UrlParameter.Optional,才允許同時訪問只傳部分值比如 只傳 arg1,或者 arg1/arg2 這樣的路徑

2、在設置默認值的情況下,如果出現 http://localhost/Home/About/arg1//arg3 這樣的鏈接,到底arg2是否有傳值進來?

3、對于http://localhost/Home/ShowAbout/11?arg1=1&arg2=2&arg3=333 這樣的鏈接,到底 arg1取的是1還是11?

以下為路由配置的代碼,并沒有為test1和test2設置參數默認值

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中的相關代碼

public JsonResult ShowAbout(string arg1, string arg2, string arg3) {return Json(arg1 + "," + arg2 + "," + arg3, JsonRequestBehavior.AllowGet);}

當我們訪問鏈接 http://localhost/Home/ShowAbout/arg1/arg2/arg3 時,會出現如下結果:

"arg1,arg2,arg3"

但如果少了一個參數,比如訪問 http://localhost/Home/ShowAbout/arg1/arg2 ,則會出現 404 的錯誤

這種情況下,需要在RouteConfig中配置默認值

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解決了不管參數是值類型還是引用類型,在未傳對應參數的情況下,都會提供一個默認值(如0或者null)

這個時候再訪問鏈接 http://localhost/Home/ShowAbout/arg1/arg2? ,則會出現如下結果,而不會報錯

"arg1,arg2,"

當我們傳入http://localhost/Home/ShowAbout/arg1//arg3,也就是故意不傳arg2的值的時候,會發現結果是

"arg1,arg3,"

也就是arg3實際傳給了參數arg2的位置,兩個//還是三個///都會被忽略成一個 /

當我們訪問 http://localhost/Home/ShowAbout/11?arg1=1&arg2=2&arg3=333 這樣的鏈接時候,發現結果是:

"11,2,333"

即當Action方法的參數是Binding類型的時候, MVC框架會將路由參數優先于查詢字符串值

?

轉載于:https://www.cnblogs.com/hxhbluestar/p/3537778.html

與50位技術專家面對面20年技術見證,附贈技術全景圖

總結

以上是生活随笔為你收集整理的ASP.NET MVC 自定义路由中几个需要注意的小细节的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。