blob: d5d2b3f24fee42ad504e26ee99388ba944e13f5a (
plain)
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
50
51
52
53
54
55
56
57
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
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 decimal values.
/// </summary>
public class DecimalRouteConstraint : IRouteConstraint, IParameterLiteralNodeMatchingPolicy
{
/// <inheritdoc />
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));
}
if (values.TryGetValue(routeKey, out var value) && value != null)
{
if (value is decimal)
{
return true;
}
var valueString = Convert.ToString(value, CultureInfo.InvariantCulture);
return CheckConstraintCore(valueString);
}
return false;
}
private static bool CheckConstraintCore(string? valueString)
{
return decimal.TryParse(valueString, NumberStyles.Number, CultureInfo.InvariantCulture, out _);
}
bool IParameterLiteralNodeMatchingPolicy.MatchesLiteral(string parameterName, string literal)
{
return CheckConstraintCore(literal);
}
}
|