-
Notifications
You must be signed in to change notification settings - Fork 179
Expand file tree
/
Copy pathApiVersionActionConstraint.cs
More file actions
91 lines (74 loc) · 2.7 KB
/
ApiVersionActionConstraint.cs
File metadata and controls
91 lines (74 loc) · 2.7 KB
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
namespace MyTested.AspNetCore.Mvc.Internal
{
using System.Linq;
using Asp.Versioning;
using Microsoft.AspNetCore.Mvc.Abstractions;
using Microsoft.AspNetCore.Mvc.ActionConstraints;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
internal class ApiVersionActionConstraint : IActionConstraint
{
public int Order => 0;
public bool Accept(ActionConstraintContext context)
{
var requestedVersion = GetRequestedApiVersion(context.RouteContext);
if (requestedVersion == null)
{
return true;
}
var metadata = context.CurrentCandidate.Action.GetApiVersionMetadata();
if (metadata == ApiVersionMetadata.Empty || metadata.IsApiVersionNeutral)
{
return true;
}
if (!metadata.IsMappedTo(requestedVersion))
{
return false;
}
if (context.Candidates.Count <= 1)
{
return true;
}
var mapping = metadata.MappingTo(requestedVersion);
if (mapping == ApiVersionMapping.Explicit)
{
return true;
}
var hasExplicitCandidate = context.Candidates.Any(c =>
{
if (c.Action == context.CurrentCandidate.Action)
{
return false;
}
var otherMetadata = c.Action.GetApiVersionMetadata();
return otherMetadata.MappingTo(requestedVersion) == ApiVersionMapping.Explicit;
});
return !hasExplicitCandidate;
}
private static ApiVersion GetRequestedApiVersion(RouteContext context)
{
var parser = ApiVersionParser.Default;
if (context.RouteData.Values.TryGetValue("version", out var routeVersion)
&& routeVersion is string versionString
&& parser.TryParse(versionString, out var parsedVersion))
{
return parsedVersion;
}
var reader = context.HttpContext.RequestServices
?.GetService<IOptions<ApiVersioningOptions>>()
?.Value
?.ApiVersionReader;
if (reader != null)
{
var rawVersions = reader.Read(context.HttpContext.Request);
if (rawVersions.Count > 0
&& parser.TryParse(rawVersions[0], out var parsedReaderVersion))
{
return parsedReaderVersion;
}
}
return null;
}
}
}