带有空参数的.NET MVC自定义路由

时间:2009-10-28 22:50:40

标签: asp.net-mvc parameters routing

我有一个.net mvc,路由如下:

routes.Add(new Route(
            "Lookups/{searchtype}/{inputtype}/{firstname}/{middlename}/{lastname}/{city}/{state}/{address}", 
            new RouteValueDictionary( new { controller = "Lookups", action = "Search", firstname = (string)null, middlename = (string)null, lastname = (string)null, city = (string)null, state = (string)null, address = (string)null, SearchType = SearchType.PeopleSearch, InputType = InputType.Name }),
            new MvcRouteHandler())
        );

        routes.Add(new Route(
            "Lookups/{searchtype}/{inputtype}", 
            new RouteValueDictionary( new { controller = "Lookups", action = "Search", firstname = "", middlename = "", lastname = "", city = "", state = "", address = "" }),
            new MvcRouteHandler())
        );

        routes.Add(new Route(
            "Lookups/{searchtype}/{inputtype}", 
            new RouteValueDictionary( new { controller = "Lookups", action = "Search", firstname = "", middlename = "", lastname = "", city = "", state = "", address = "", SearchType = SearchType.PeopleSearch, InputType = InputType.Name }),
            new MvcRouteHandler())
        );

        routes.MapRoute(
            "Default",                                              // Route name
            "{controller}/{action}/{id}",                           // URL with parameters
            new { controller = "Account", action = "LogOn", id = "" }  // Parameter defaults
        );

以下请求正常:

http://localhost:2608/Lookups/PeopleSearch/Name/john/w/smith/seattle/wa/123主要

此请求不起作用:

http://localhost:2608/Lookups/PeopleSearch/Name/john//smith//wa/

并非所有请求都包含所有参数,我希望将空参数作为空字符串或null传递给方法。

我哪里错了?

方法:

public ActionResult Search(string firstname, string middlename, string lastname, string city, string state, string address, SearchType searchtype, InputType inputtype)
    {
        SearchRequest r = new SearchRequest { Firstname = firstname, Middlename = middlename, Lastname = lastname, City = city, State = state, Address = address, SearchType = searchtype, InputType = inputtype };
        return View(r);
    }

1 个答案:

答案 0 :(得分:2)

我看到一个问题,您的第二条和第三条路线具有完全相同的网址参数。所以第三条路线永远不会被召唤。你为什么那么?看起来你可以简单地删除第二条路线。

此外,第二条路线的参数少于第一条路线。这意味着第一条路线可能会匹配您发布的两个网址。您应该重新订购这些路线。

更新:哦!我没有注意到URL中的双斜杠。那永远不会奏效。就ASP.NET而言,它不是一个有效的URL,因此ASP.NET甚至在它到达路由之前就阻止了它。