// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Globalization; using Microsoft.AspNetCore.Http; namespace Microsoft.AspNetCore.Routing.Constraints { /// /// Constraints a route parameter to be an integer within a given range of values. /// public class RangeRouteConstraint : IRouteConstraint { /// /// Initializes a new instance of the class. /// /// The minimum value. /// The maximum value. /// The minimum value should be less than or equal to the maximum value. public RangeRouteConstraint(long min, long max) { if (min > max) { var errorMessage = Resources.FormatRangeConstraint_MinShouldBeLessThanOrEqualToMax("min", "max"); throw new ArgumentOutOfRangeException(nameof(min), min, errorMessage); } Min = min; Max = max; } /// /// Gets the minimum allowed value of the route parameter. /// public long Min { get; private set; } /// /// Gets the maximum allowed value of the route parameter. /// public long Max { get; private set; } /// public bool Match( HttpContext httpContext, IRouter route, string routeKey, RouteValueDictionary values, RouteDirection routeDirection) { if (routeKey == null) { throw new ArgumentNullException(nameof(routeKey)); } if (values == null) { throw new ArgumentNullException(nameof(values)); } object value; if (values.TryGetValue(routeKey, out value) && value != null) { long longValue; var valueString = Convert.ToString(value, CultureInfo.InvariantCulture); if (Int64.TryParse(valueString, NumberStyles.Integer, CultureInfo.InvariantCulture, out longValue)) { return longValue >= Min && longValue <= Max; } } return false; } } }