gpt4 book ai didi

asp.net-mvc-4 - 如何在 ASP.NET MVC4 上将路由值限制为有效的 int32

转载 作者:行者123 更新时间:2023-12-02 01:09:55 25 4
gpt4 key购买 nike

有这个默认路由:

    routes.MapRoute(
name: "Default", // Route name
url: "{controller}/{action}/{id}", // URL with parameters
defaults: new { controller = "Application", action = "Index", id = 0 }, // Parameter defaults
constraints: new {id = @"\d+"}
);

约束工作正常,但 id 在 Controller 上是一个 int。因此,如果我传递的 /Controller/Action/2147483648 是一个有效的\d+ 正则表达式,但它不是一个有效的 Int32,因此返回 500 服务器错误,我希望它限制以便它返回 404

我怎样才能使约束只允许有效的正 int 值?从 0 到 2,147,483,647 ?

最佳答案

您可以像这样创建自定义路由约束:

public class MaxIntConstraint : IRouteConstraint
{
public bool Match (HttpContextBase httpContext, Route route, string parameterName,
RouteValueDictionary values, RouteDirection routeDirection)
{
// just use int.TryParse because if it can't fit it won't parse
int val;
return int.TryParse(values[parameterName].ToString(), out val);
}
}

你的路线看起来像这样:

routes.MapRoute(
name: "Default", // Route name
url: "{controller}/{action}/{id}", // URL with parameters
defaults: new { controller = "Application", action = "Index", id = 0 }, // Parameter defaults
constraints: new { id = new MaxIntConstraint() }
);

当然,约束是非常具体的,可以通过更多的错误检查来修饰,但你明白了。

关于asp.net-mvc-4 - 如何在 ASP.NET MVC4 上将路由值限制为有效的 int32,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18386813/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com