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框架会将路由参数优先于查询字符串值

 

posted on 2014-02-04 10:24  团团ta爸  阅读(1613)  评论(2编辑  收藏  举报

导航