【问题标题】:ASP.Net MVC routing with RouteConstraint not working带有 RouteConstraint 的 ASP.Net MVC 路由不起作用
【发布时间】:2012-08-08 16:04:32
【问题描述】:

就在我认为我已经确定了路由时,它并没有按照我认为的方式工作。我正在使用 ASP.Net MVC 4 RC。这是我的 RouteConfig:

        routes.MapRoute
        (
            "TwoIntegers",
            "{controller}/{action}/{id1}/{id2}",
            new { controller = "Gallery", action = "Index", id1 = new Int32Constraint(), id2 = new Int32Constraint() }
        );

        routes.MapRoute
        (
            "Default",
            "{controller}/{action}/{id}",
            new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );

这是我的路线限制:

public class Int32Constraint : IRouteConstraint
{
    public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
    {
        if (values.ContainsKey(parameterName))
        {
            int intValue;
            return int.TryParse(values[parameterName].ToString(), out intValue) && (intValue != int.MinValue) && (intValue != int.MaxValue);
        }

        return false;
    }
}

/{domain.com}/PageSection/Edit/21

它在“TwoIntegers”路线处停止。很明显,没有传递第二个整数。

这是我的错误:

参数字典包含参数“id”的空条目 方法的不可空类型“System.Int32” 'System.Web.Mvc.ActionResult Edit(Int32)' 在 'SolutiaConsulting.Web.ContentManager.Controllers.PageSectionController'。 可选参数必须是引用类型、可空类型或 声明为可选参数。参数名称:参数

我做错了什么?我首先列出了更具体的路线。请帮忙。

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-routing


    【解决方案1】:

    您的约束未正确指定。确保您使用的是 MapRoute 扩展方法的正确重载:

    routes.MapRoute(
        "TwoIntegers",
        "{controller}/{action}/{id1}/{id2}",
        new { controller = "Gallery", action = "Index" },
        new { id1 = new Int32Constraint(), id2 = new Int32Constraint() }
    );
    

    注意用于指定约束的第四个参数,而不是第三个。

    顺便说一句,您可以使用命名参数使您的代码更具可读性:

    routes.MapRoute(
        name: "TwoIntegers",
        url: "{controller}/{action}/{id1}/{id2}",
        defaults: new { controller = "Gallery", action = "Index" },
        constraints: new { id1 = new Int32Constraint(), id2 = new Int32Constraint() }
    );
    

    还有一个正则表达式怎么样?

    routes.MapRoute(
        name: "TwoIntegers",
        url: "{controller}/{action}/{id1}/{id2}",
        defaults: new { controller = "Gallery", action = "Index" },
        constraints: new { id1 = @"\d+", id2 = @"\d+" }
    );
    

    【讨论】:

    • 正则表达式解决方案不会有溢出整数值的问题吗?例如如果用户为 id1 或 id2 输入一个大于 Int32.MaxValue 的值,它会中断吗?
    猜你喜欢
    • 2017-02-20
    • 1970-01-01
    • 2013-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-02
    • 2017-11-08
    相关资源
    最近更新 更多