forked from aspnet/AspNetWebStack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHttpRoute.cs
More file actions
307 lines (261 loc) · 12.5 KB
/
HttpRoute.cs
File metadata and controls
307 lines (261 loc) · 12.5 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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
// 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.Generic;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Text.RegularExpressions;
using System.Web.Http.Properties;
namespace System.Web.Http.Routing
{
/// <summary>
/// Route class for self-host (i.e. hosted outside of ASP.NET). This class is mostly the
/// same as the System.Web.Routing.Route implementation.
/// This class has the same URL matching functionality as System.Web.Routing.Route. However,
/// in order for this route to match when generating URLs, a special "httproute" key must be
/// specified when generating the URL.
/// </summary>
public class HttpRoute : IHttpRoute
{
/// <summary>
/// Key used to signify that a route URL generation request should include HTTP routes (e.g. Web API).
/// If this key is not specified then no HTTP routes will match.
/// </summary>
public static readonly string HttpRouteKey = "httproute";
internal const string RoutingContextKey = "MS_RoutingContext";
private string _routeTemplate;
private HttpRouteValueDictionary _defaults;
private HttpRouteValueDictionary _constraints;
private HttpRouteValueDictionary _dataTokens;
public HttpRoute()
: this(routeTemplate: null, defaults: null, constraints: null, dataTokens: null, handler: null, parsedRoute: null)
{
}
public HttpRoute(string routeTemplate)
: this(routeTemplate, defaults: null, constraints: null, dataTokens: null, handler: null, parsedRoute: null)
{
}
public HttpRoute(string routeTemplate, HttpRouteValueDictionary defaults)
: this(routeTemplate, defaults, constraints: null, dataTokens: null, handler: null, parsedRoute: null)
{
}
public HttpRoute(string routeTemplate, HttpRouteValueDictionary defaults, HttpRouteValueDictionary constraints)
: this(routeTemplate, defaults, constraints, dataTokens: null, handler: null, parsedRoute: null)
{
}
public HttpRoute(string routeTemplate, HttpRouteValueDictionary defaults, HttpRouteValueDictionary constraints, HttpRouteValueDictionary dataTokens)
: this(routeTemplate, defaults, constraints, dataTokens, handler: null, parsedRoute: null)
{
}
public HttpRoute(string routeTemplate, HttpRouteValueDictionary defaults, HttpRouteValueDictionary constraints, HttpRouteValueDictionary dataTokens, HttpMessageHandler handler)
: this(routeTemplate, defaults, constraints, dataTokens, handler, parsedRoute: null)
{
}
internal HttpRoute(string routeTemplate, HttpRouteValueDictionary defaults, HttpRouteValueDictionary constraints, HttpRouteValueDictionary dataTokens, HttpMessageHandler handler, HttpParsedRoute parsedRoute)
{
_routeTemplate = routeTemplate == null ? String.Empty : routeTemplate;
_defaults = defaults ?? new HttpRouteValueDictionary();
_constraints = constraints ?? new HttpRouteValueDictionary();
_dataTokens = dataTokens ?? new HttpRouteValueDictionary();
Handler = handler;
if (parsedRoute == null)
{
// The parser will throw for invalid routes.
ParsedRoute = RouteParser.Parse(routeTemplate);
}
else
{
ParsedRoute = parsedRoute;
}
}
public IDictionary<string, object> Defaults
{
get { return _defaults; }
}
public IDictionary<string, object> Constraints
{
get { return _constraints; }
}
public IDictionary<string, object> DataTokens
{
get { return _dataTokens; }
}
public HttpMessageHandler Handler { get; private set; }
public string RouteTemplate
{
get { return _routeTemplate; }
}
internal HttpParsedRoute ParsedRoute { get; private set; }
public virtual IHttpRouteData GetRouteData(string virtualPathRoot, HttpRequestMessage request)
{
if (virtualPathRoot == null)
{
throw Error.ArgumentNull("virtualPathRoot");
}
if (request == null)
{
throw Error.ArgumentNull("request");
}
RoutingContext context = GetOrCreateRoutingContext(virtualPathRoot, request);
if (!context.IsValid)
{
return null;
}
HttpRouteValueDictionary values = ParsedRoute.Match(context, _defaults);
if (values == null)
{
// If we got back a null value set, that means the URI did not match
return null;
}
// Validate the values
if (!ProcessConstraints(request, values, HttpRouteDirection.UriResolution))
{
return null;
}
return new HttpRouteData(this, values);
}
private static RoutingContext GetOrCreateRoutingContext(string virtualPathRoot, HttpRequestMessage request)
{
RoutingContext context;
if (!request.Properties.TryGetValue<RoutingContext>(RoutingContextKey, out context))
{
context = CreateRoutingContext(virtualPathRoot, request);
request.Properties[RoutingContextKey] = context;
}
return context;
}
private static RoutingContext CreateRoutingContext(string virtualPathRoot, HttpRequestMessage request)
{
// Note: we don't validate host/port as this is expected to be done at the host level
string requestPath = "/" + request.RequestUri.GetComponents(UriComponents.Path, UriFormat.Unescaped);
// This code is optimized for the common path being an exact case match on the virtual path string.
// An Ordinal (case-sensitive) comparison is significantly faster than OrdinalIgnoreCase.
if (!requestPath.StartsWith(virtualPathRoot, StringComparison.Ordinal))
{
if (!requestPath.StartsWith(virtualPathRoot, StringComparison.OrdinalIgnoreCase))
{
return RoutingContext.Invalid();
}
}
string relativeRequestPath = null;
int virtualPathLength = virtualPathRoot.Length;
if (requestPath.Length > virtualPathLength && requestPath[virtualPathLength] == '/')
{
relativeRequestPath = requestPath.Substring(virtualPathLength + 1);
}
else
{
relativeRequestPath = requestPath.Substring(virtualPathLength);
}
return RoutingContext.Valid(RouteParser.SplitUriToPathSegmentStrings(relativeRequestPath));
}
/// <summary>
/// Attempt to generate a URI that represents the values passed in based on current
/// values from the <see cref="HttpRouteData"/> and new values using the specified <see cref="HttpRoute"/>.
/// </summary>
/// <param name="request">The HTTP request message.</param>
/// <param name="values">The route values.</param>
/// <returns>A <see cref="HttpVirtualPathData"/> instance or null if URI cannot be generated.</returns>
public virtual IHttpVirtualPathData GetVirtualPath(HttpRequestMessage request, IDictionary<string, object> values)
{
if (request == null)
{
throw Error.ArgumentNull("request");
}
// Only perform URL generation if the "httproute" key was specified. This allows these
// routes to be ignored when a regular MVC app tries to generate URLs. Without this special
// key an HTTP route used for Web API would normally take over almost all the routes in a
// typical app.
if (values != null && !values.Keys.Contains(HttpRouteKey, StringComparer.OrdinalIgnoreCase))
{
return null;
}
// Remove the value from the collection so that it doesn't affect the generated URL
var newValues = GetRouteDictionaryWithoutHttpRouteKey(values);
IHttpRouteData routeData = request.GetRouteData();
IDictionary<string, object> requestValues = routeData == null ? null : routeData.Values;
BoundRouteTemplate result = ParsedRoute.Bind(requestValues, newValues, _defaults, _constraints);
if (result == null)
{
return null;
}
// Verify that the route matches the validation rules
if (!ProcessConstraints(request, result.Values, HttpRouteDirection.UriGeneration))
{
return null;
}
return new HttpVirtualPathData(this, result.BoundTemplate);
}
private static IDictionary<string, object> GetRouteDictionaryWithoutHttpRouteKey(IDictionary<string, object> routeValues)
{
var newRouteValues = new HttpRouteValueDictionary();
if (routeValues != null)
{
foreach (var routeValue in routeValues)
{
if (!String.Equals(routeValue.Key, HttpRouteKey, StringComparison.OrdinalIgnoreCase))
{
newRouteValues.Add(routeValue.Key, routeValue.Value);
}
}
}
return newRouteValues;
}
protected virtual bool ProcessConstraint(HttpRequestMessage request, object constraint, string parameterName, HttpRouteValueDictionary values, HttpRouteDirection routeDirection)
{
IHttpRouteConstraint customConstraint = constraint as IHttpRouteConstraint;
if (customConstraint != null)
{
return customConstraint.Match(request, this, parameterName, values, routeDirection);
}
// If there was no custom constraint, then treat the constraint as a string which represents a Regex.
string constraintsRule = constraint as string;
if (constraintsRule == null)
{
throw Error.InvalidOperation(SRResources.Route_ValidationMustBeStringOrCustomConstraint, parameterName, RouteTemplate, typeof(IHttpRouteConstraint).Name);
}
object parameterValue;
values.TryGetValue(parameterName, out parameterValue);
string parameterValueString = Convert.ToString(parameterValue, CultureInfo.InvariantCulture);
string constraintsRegEx = "^(" + constraintsRule + ")$";
return Regex.IsMatch(parameterValueString, constraintsRegEx, RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);
}
private bool ProcessConstraints(HttpRequestMessage request, HttpRouteValueDictionary values, HttpRouteDirection routeDirection)
{
if (Constraints != null)
{
foreach (KeyValuePair<string, object> constraintsItem in Constraints)
{
if (!ProcessConstraint(request, constraintsItem.Value, constraintsItem.Key, values, routeDirection))
{
return false;
}
}
}
return true;
}
// Validates that a constraint is of a type that HttpRoute can process. This is not valid to
// call when a route implements IHttpRoute or inherits from HttpRoute - as the derived class can handle
// any types of constraints it wants to support.
internal static void ValidateConstraint(string routeTemplate, string name, object constraint)
{
if (constraint is IHttpRouteConstraint)
{
return;
}
if (constraint is string)
{
return;
}
throw CreateInvalidConstraintTypeException(routeTemplate, name);
}
private static Exception CreateInvalidConstraintTypeException(string routeTemplate, string name)
{
return Error.InvalidOperation(
SRResources.Route_ValidationMustBeStringOrCustomConstraint,
name,
routeTemplate,
typeof(IHttpRouteConstraint).FullName);
}
}
}