forked from aspnet/AspNetWebStack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDefaultHttpControllerSelector.cs
More file actions
232 lines (198 loc) · 9.67 KB
/
Copy pathDefaultHttpControllerSelector.cs
File metadata and controls
232 lines (198 loc) · 9.67 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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web.Http.Controllers;
using System.Web.Http.Properties;
using System.Web.Http.Routing;
namespace System.Web.Http.Dispatcher
{
/// <summary>
/// Default <see cref="IHttpControllerSelector"/> instance for choosing a <see cref="HttpControllerDescriptor"/> given a <see cref="HttpRequestMessage"/>
/// A different implementation can be registered via the <see cref="HttpConfiguration.Services"/>.
/// </summary>
public class DefaultHttpControllerSelector : IHttpControllerSelector
{
public static readonly string ControllerSuffix = "Controller";
private const string ControllerKey = "controller";
private readonly HttpConfiguration _configuration;
private readonly HttpControllerTypeCache _controllerTypeCache;
private readonly Lazy<ConcurrentDictionary<string, HttpControllerDescriptor>> _controllerInfoCache;
/// <summary>
/// Initializes a new instance of the <see cref="DefaultHttpControllerSelector"/> class.
/// </summary>
/// <param name="configuration">The configuration.</param>
public DefaultHttpControllerSelector(HttpConfiguration configuration)
{
if (configuration == null)
{
throw Error.ArgumentNull("configuration");
}
_controllerInfoCache = new Lazy<ConcurrentDictionary<string, HttpControllerDescriptor>>(InitializeControllerInfoCache);
_configuration = configuration;
_controllerTypeCache = new HttpControllerTypeCache(_configuration);
}
[SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Caller is responsible for disposing of response instance.")]
public virtual HttpControllerDescriptor SelectController(HttpRequestMessage request)
{
if (request == null)
{
throw Error.ArgumentNull("request");
}
IHttpRouteData routeData = request.GetRouteData();
HttpControllerDescriptor controllerDescriptor;
if (routeData != null)
{
controllerDescriptor = GetDirectRouteController(routeData);
if (controllerDescriptor != null)
{
return controllerDescriptor;
}
}
string controllerName = GetControllerName(request);
if (String.IsNullOrEmpty(controllerName))
{
throw new HttpResponseException(request.CreateErrorResponse(
HttpStatusCode.NotFound,
Error.Format(SRResources.ResourceNotFound, request.RequestUri),
Error.Format(SRResources.ControllerNameNotFound, request.RequestUri)));
}
if (_controllerInfoCache.Value.TryGetValue(controllerName, out controllerDescriptor))
{
return controllerDescriptor;
}
ICollection<Type> matchingTypes = _controllerTypeCache.GetControllerTypes(controllerName);
// ControllerInfoCache is already initialized.
Contract.Assert(matchingTypes.Count != 1);
if (matchingTypes.Count == 0)
{
// no matching types
throw new HttpResponseException(request.CreateErrorResponse(
HttpStatusCode.NotFound,
Error.Format(SRResources.ResourceNotFound, request.RequestUri),
Error.Format(SRResources.DefaultControllerFactory_ControllerNameNotFound, controllerName)));
}
else
{
// multiple matching types
throw CreateAmbiguousControllerException(request.GetRouteData().Route, controllerName, matchingTypes);
}
}
public virtual IDictionary<string, HttpControllerDescriptor> GetControllerMapping()
{
return _controllerInfoCache.Value.ToDictionary(c => c.Key, c => c.Value, StringComparer.OrdinalIgnoreCase);
}
public virtual string GetControllerName(HttpRequestMessage request)
{
if (request == null)
{
throw Error.ArgumentNull("request");
}
IHttpRouteData routeData = request.GetRouteData();
if (routeData == null)
{
return null;
}
// Look up controller in route data
string controllerName = null;
routeData.Values.TryGetValue(ControllerKey, out controllerName);
return controllerName;
}
// If routeData is from an attribute route, get the controller that can handle it.
// Else return null. Throws an exception if multiple controllers match
private static HttpControllerDescriptor GetDirectRouteController(IHttpRouteData routeData)
{
CandidateAction[] candidates = routeData.GetDirectRouteCandidates();
if (candidates != null)
{
// Set the controller descriptor for the first action descriptor
Contract.Assert(candidates.Length > 0);
Contract.Assert(candidates[0].ActionDescriptor != null);
HttpControllerDescriptor controllerDescriptor = candidates[0].ActionDescriptor.ControllerDescriptor;
// Check that all other candidate action descriptors share the same controller descriptor
for (int i = 1; i < candidates.Length; i++)
{
CandidateAction candidate = candidates[i];
if (candidate.ActionDescriptor.ControllerDescriptor != controllerDescriptor)
{
// We've found an ambiguity (multiple controllers matched)
throw CreateDirectRouteAmbiguousControllerException(candidates);
}
}
return controllerDescriptor;
}
return null;
}
private static Exception CreateDirectRouteAmbiguousControllerException(CandidateAction[] candidates)
{
Contract.Assert(candidates != null);
Contract.Assert(candidates.Length > 1);
HashSet<Type> matchingTypes = new HashSet<Type>();
for (int i = 0; i < candidates.Length; i++)
{
matchingTypes.Add(candidates[i].ActionDescriptor.ControllerDescriptor.ControllerType);
}
// we need to generate an exception containing all the controller types
StringBuilder typeList = new StringBuilder();
foreach (Type matchedType in matchingTypes)
{
typeList.AppendLine();
typeList.Append(matchedType.FullName);
}
return Error.InvalidOperation(SRResources.DirectRoute_AmbiguousController, typeList, Environment.NewLine);
}
private static Exception CreateAmbiguousControllerException(IHttpRoute route, string controllerName, ICollection<Type> matchingTypes)
{
Contract.Assert(route != null);
Contract.Assert(controllerName != null);
Contract.Assert(matchingTypes != null);
// Generate an exception containing all the controller types
StringBuilder typeList = new StringBuilder();
foreach (Type matchedType in matchingTypes)
{
typeList.AppendLine();
typeList.Append(matchedType.FullName);
}
string errorMessage = Error.Format(SRResources.DefaultControllerFactory_ControllerNameAmbiguous_WithRouteTemplate, controllerName, route.RouteTemplate, typeList, Environment.NewLine);
return new InvalidOperationException(errorMessage);
}
private ConcurrentDictionary<string, HttpControllerDescriptor> InitializeControllerInfoCache()
{
var result = new ConcurrentDictionary<string, HttpControllerDescriptor>(StringComparer.OrdinalIgnoreCase);
var duplicateControllers = new HashSet<string>();
Dictionary<string, ILookup<string, Type>> controllerTypeGroups = _controllerTypeCache.Cache;
foreach (KeyValuePair<string, ILookup<string, Type>> controllerTypeGroup in controllerTypeGroups)
{
string controllerName = controllerTypeGroup.Key;
foreach (IGrouping<string, Type> controllerTypesGroupedByNs in controllerTypeGroup.Value)
{
foreach (Type controllerType in controllerTypesGroupedByNs)
{
if (result.Keys.Contains(controllerName))
{
duplicateControllers.Add(controllerName);
break;
}
else
{
result.TryAdd(controllerName, new HttpControllerDescriptor(_configuration, controllerName, controllerType));
}
}
}
}
foreach (string duplicateController in duplicateControllers)
{
HttpControllerDescriptor descriptor;
result.TryRemove(duplicateController, out descriptor);
}
return result;
}
}
}