-
Notifications
You must be signed in to change notification settings - Fork 9.8k
/
ApiConventionResult.cs
72 lines (62 loc) · 2.61 KB
/
ApiConventionResult.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Reflection;
namespace Microsoft.AspNetCore.Mvc.ApiExplorer;
/// <summary>
/// Metadata associated with an action method via API convention.
/// </summary>
public sealed class ApiConventionResult
{
/// <summary>
/// Initializes a new instance of <see cref="ApiConventionResult"/>.
/// </summary>
/// <param name="responseMetadataProviders">The sequence of <see cref="IApiResponseMetadataProvider"/> that are associated with the action.</param>
public ApiConventionResult(IReadOnlyList<IApiResponseMetadataProvider> responseMetadataProviders)
{
ResponseMetadataProviders = responseMetadataProviders ??
throw new ArgumentNullException(nameof(responseMetadataProviders));
}
/// <summary>
/// Gets the sequence of <see cref="IApiResponseMetadataProvider"/> that are associated with the action.
/// </summary>
public IReadOnlyList<IApiResponseMetadataProvider> ResponseMetadataProviders { get; }
internal static bool TryGetApiConvention(
MethodInfo method,
ApiConventionTypeAttribute[] apiConventionAttributes,
[NotNullWhen(true)] out ApiConventionResult? result)
{
var apiConventionMethodAttribute = method.GetCustomAttribute<ApiConventionMethodAttribute>(inherit: true);
var conventionMethod = apiConventionMethodAttribute?.Method;
if (conventionMethod == null)
{
conventionMethod = GetConventionMethod(method, apiConventionAttributes);
}
if (conventionMethod != null)
{
var metadataProviders = conventionMethod.GetCustomAttributes(inherit: false)
.OfType<IApiResponseMetadataProvider>()
.ToArray();
result = new ApiConventionResult(metadataProviders);
return true;
}
result = null;
return false;
}
private static MethodInfo? GetConventionMethod(MethodInfo method, ApiConventionTypeAttribute[] apiConventionAttributes)
{
foreach (var attribute in apiConventionAttributes)
{
var conventionMethods = attribute.ConventionType.GetMethods(BindingFlags.Public | BindingFlags.Static);
foreach (var conventionMethod in conventionMethods)
{
if (ApiConventionMatcher.IsMatch(method, conventionMethod))
{
return conventionMethod;
}
}
}
return null;
}
}