-
Notifications
You must be signed in to change notification settings - Fork 179
Expand file tree
/
Copy pathApiVersionAwareActionSelector.cs
More file actions
99 lines (81 loc) · 3.15 KB
/
ApiVersionAwareActionSelector.cs
File metadata and controls
99 lines (81 loc) · 3.15 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
92
93
94
95
96
97
98
99
namespace MyTested.AspNetCore.Mvc.Internal
{
using System.Collections.Generic;
using System.Linq;
using Asp.Versioning;
using Microsoft.AspNetCore.Mvc.Abstractions;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
internal class ApiVersionAwareActionSelector : IActionSelector
{
private readonly IActionSelector inner;
public ApiVersionAwareActionSelector(IActionSelector inner)
{
this.inner = inner;
}
public IReadOnlyList<ActionDescriptor> SelectCandidates(RouteContext context)
=> this.inner.SelectCandidates(context);
public ActionDescriptor SelectBestCandidate(
RouteContext context,
IReadOnlyList<ActionDescriptor> candidates)
{
var requestedVersion = GetRequestedApiVersion(context);
if (requestedVersion == null)
{
return this.inner.SelectBestCandidate(context, candidates);
}
var versionedCandidates = new List<ActionDescriptor>();
foreach (var candidate in candidates)
{
var metadata = candidate.GetApiVersionMetadata();
if (metadata == ApiVersionMetadata.Empty
|| metadata.IsApiVersionNeutral
|| metadata.IsMappedTo(requestedVersion))
{
versionedCandidates.Add(candidate);
}
}
if (versionedCandidates.Count == 0)
{
return null;
}
if (versionedCandidates.Count > 1)
{
var explicitlyMapped = versionedCandidates
.Where(c => c.GetApiVersionMetadata().MappingTo(requestedVersion) == ApiVersionMapping.Explicit)
.ToList();
if (explicitlyMapped.Count > 0)
{
versionedCandidates = explicitlyMapped;
}
}
return this.inner.SelectBestCandidate(context, versionedCandidates);
}
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;
}
}
}