/
LongRouteConstraint.cs
49 lines (41 loc) · 1.49 KB
/
LongRouteConstraint.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Globalization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing.Matching;
namespace Microsoft.AspNetCore.Routing.Constraints;
/// <summary>
/// Constrains a route parameter to represent only 64-bit integer values.
/// </summary>
public class LongRouteConstraint : IRouteConstraint, IParameterLiteralNodeMatchingPolicy, ICachableParameterPolicy
{
/// <inheritdoc />
public bool Match(
HttpContext? httpContext,
IRouter? route,
string routeKey,
RouteValueDictionary values,
RouteDirection routeDirection)
{
ArgumentNullException.ThrowIfNull(routeKey);
ArgumentNullException.ThrowIfNull(values);
if (values.TryGetValue(routeKey, out var value) && value != null)
{
if (value is long)
{
return true;
}
var valueString = Convert.ToString(value, CultureInfo.InvariantCulture);
return CheckConstraintCore(valueString);
}
return false;
}
private static bool CheckConstraintCore(string? valueString)
{
return long.TryParse(valueString, NumberStyles.Integer, CultureInfo.InvariantCulture, out _);
}
bool IParameterLiteralNodeMatchingPolicy.MatchesLiteral(string parameterName, string literal)
{
return CheckConstraintCore(literal);
}
}