forked from haoduotnt/aspnetwebstack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApiController.cs
More file actions
518 lines (457 loc) · 23.9 KB
/
ApiController.cs
File metadata and controls
518 lines (457 loc) · 23.9 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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Net;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Security.Principal;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Http.Controllers;
using System.Web.Http.Dispatcher;
using System.Web.Http.Filters;
using System.Web.Http.Hosting;
using System.Web.Http.ModelBinding;
using System.Web.Http.Properties;
using System.Web.Http.Results;
using System.Web.Http.Routing;
using Newtonsoft.Json;
namespace System.Web.Http
{
public abstract class ApiController : IHttpController, IDisposable
{
private bool _disposed;
private ModelStateDictionary _modelState;
private HttpControllerContext _controllerContext;
private IHostPrincipalService _principalService;
private bool _initialized;
/// <summary>Gets the configuration.</summary>
/// <remarks>The setter is intended for unit testing purposes only.</remarks>
public HttpConfiguration Configuration
{
get { return ControllerContext.Configuration; }
set
{
ControllerContext.Configuration = value;
}
}
/// <summary>Gets the controller context.</summary>
/// <remarks>The setter is intended for unit testing purposes only.</remarks>
public HttpControllerContext ControllerContext
{
get
{
// unit test only.
if (_controllerContext == null)
{
_controllerContext = new HttpControllerContext();
}
return _controllerContext;
}
set
{
if (value == null)
{
throw Error.PropertyNull();
}
_controllerContext = value;
}
}
/// <summary>
/// Gets model state after the model binding process. This ModelState will be empty before model binding happens.
/// </summary>
/// <remarks>The setter is intended for unit testing purposes only.</remarks>
public ModelStateDictionary ModelState
{
get
{
if (_modelState == null)
{
// The getter is not intended to be used by multiple threads, so it is fine to initialize here.
_modelState = new ModelStateDictionary();
}
return _modelState;
}
internal set
{
Contract.Assert(value != null);
_modelState = value;
}
}
/// <summary>Gets the HTTP request message.</summary>
/// <remarks>The setter is intended for unit testing purposes only.</remarks>
public HttpRequestMessage Request
{
get { return ControllerContext.Request; }
set
{
ControllerContext.Request = value;
// Unit testing only
if (Request.GetRequestContext() == null)
{
Request.SetRequestContext(RequestContext);
}
}
}
/// <summary>Gets the request context.</summary>
/// <remarks>The setter is intended for unit testing purposes only.</remarks>
public HttpRequestContext RequestContext
{
get { return ControllerContext.RequestContext; }
set { ControllerContext.RequestContext = value; }
}
/// <summary>Gets a factory used to generate URLs to other APIs.</summary>
/// <remarks>The setter is intended for unit testing purposes only.</remarks>
public UrlHelper Url
{
get { return RequestContext.Url ?? (Request != null ? new UrlHelper(Request) : null); }
set { RequestContext.Url = value; }
}
/// <summary>
/// Returns the current principal associated with this request.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification = "That would make for poor usability.")]
public IPrincipal User
{
get { return RequestContext.Principal; }
set { RequestContext.Principal = value; }
}
[SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling", Justification = "This method is a coordinator, so this coupling is expected.")]
public virtual Task<HttpResponseMessage> ExecuteAsync(HttpControllerContext controllerContext, CancellationToken cancellationToken)
{
if (_initialized)
{
// if user has registered a controller factory which produces the same controller instance, we should throw here
throw Error.InvalidOperation(SRResources.CannotSupportSingletonInstance, typeof(ApiController).Name, typeof(IHttpControllerActivator).Name);
}
Initialize(controllerContext);
// We can't be reused, and we know we're disposable, so make sure we go away when
// the request has been completed.
if (Request != null)
{
Request.RegisterForDispose(this);
}
HttpControllerDescriptor controllerDescriptor = controllerContext.ControllerDescriptor;
ServicesContainer controllerServices = controllerDescriptor.Configuration.Services;
HttpActionDescriptor actionDescriptor = controllerServices.GetActionSelector().SelectAction(controllerContext);
if (Request != null)
{
Request.SetActionDescriptor(actionDescriptor);
}
HttpActionContext actionContext = new HttpActionContext(controllerContext, actionDescriptor);
FilterGrouping filterGrouping = actionDescriptor.GetFilterGrouping();
IActionFilter[] actionFilters = filterGrouping.ActionFilters;
IAuthenticationFilter[] authenticationFilters = filterGrouping.AuthenticationFilters;
IAuthorizationFilter[] authorizationFilters = filterGrouping.AuthorizationFilters;
IExceptionFilter[] exceptionFilters = filterGrouping.ExceptionFilters;
IHttpActionResult result = new ActionFilterResult(actionDescriptor.ActionBinding, actionContext, this,
controllerServices, actionFilters);
if (authorizationFilters.Length > 0)
{
result = new AuthorizationFilterResult(actionContext, authorizationFilters, result);
}
if (authenticationFilters.Length > 0)
{
result = new AuthenticationFilterResult(actionContext, this, authenticationFilters, _principalService,
controllerContext.Request, result);
}
return InvokeActionWithExceptionFilters(result, actionContext, cancellationToken, exceptionFilters);
}
/// <summary>Creates a <see cref="BadRequestResult"/> (400 Bad Request).</summary>
/// <returns>A <see cref="BadRequestResult"/>.</returns>
protected internal virtual BadRequestResult BadRequest()
{
return new BadRequestResult(this);
}
/// <summary>
/// Creates a <see cref="BadRequestErrorMessageResult"/> (400 Bad Request) with the specified error message.
/// </summary>
/// <param name="message">The user-visible error message.</param>
/// <returns>A <see cref="BadRequestErrorMessageResult"/> with the specified error message.</returns>
protected internal virtual BadRequestErrorMessageResult BadRequest(string message)
{
return new BadRequestErrorMessageResult(message, this);
}
/// <summary>
/// Creates an <see cref="InvalidModelStateResult"/> (400 Bad Request) with the specified model state.
/// </summary>
/// <param name="modelState">The model state to include in the error.</param>
/// <returns>An <see cref="InvalidModelStateResult"/> with the specified model state.</returns>
protected internal virtual InvalidModelStateResult BadRequest(ModelStateDictionary modelState)
{
return new InvalidModelStateResult(modelState, this);
}
/// <summary>Creates a <see cref="ConflictResult"/> (409 Conflict).</summary>
/// <returns>A <see cref="ConflictResult"/>.</returns>
protected internal virtual ConflictResult Conflict()
{
return new ConflictResult(this);
}
/// <summary>Creates a <see cref="NegotiatedContentResult{T}"/> with the specified values.</summary>
/// <typeparam name="T">The type of content in the entity body.</typeparam>
/// <param name="statusCode">The HTTP status code for the response message.</param>
/// <param name="value">The content value to negotiate and format in the entity body.</param>
/// <returns>A <see cref="NegotiatedContentResult{T}"/> with the specified values.</returns>
protected internal virtual NegotiatedContentResult<T> Content<T>(HttpStatusCode statusCode, T value)
{
return new NegotiatedContentResult<T>(statusCode, value, this);
}
/// <summary>Creates a <see cref="FormattedContentResult{T}"/> with the specified values.</summary>
/// <typeparam name="T">The type of content in the entity body.</typeparam>
/// <param name="statusCode">The HTTP status code for the response message.</param>
/// <param name="value">The content value to format in the entity body.</param>
/// <param name="formatter">The formatter to use to format the content.</param>
/// <returns>A <see cref="FormattedContentResult{T}"/> with the specified values.</returns>
protected internal FormattedContentResult<T> Content<T>(HttpStatusCode statusCode, T value,
MediaTypeFormatter formatter)
{
return Content(statusCode, value, formatter, (MediaTypeHeaderValue)null);
}
/// <summary>Creates a <see cref="FormattedContentResult{T}"/> with the specified values.</summary>
/// <typeparam name="T">The type of content in the entity body.</typeparam>
/// <param name="statusCode">The HTTP status code for the response message.</param>
/// <param name="value">The content value to format in the entity body.</param>
/// <param name="formatter">The formatter to use to format the content.</param>
/// <param name="mediaType">The value for the Content-Type header.</param>
/// <returns>A <see cref="FormattedContentResult{T}"/> with the specified values.</returns>
protected internal FormattedContentResult<T> Content<T>(HttpStatusCode statusCode, T value,
MediaTypeFormatter formatter, string mediaType)
{
return Content(statusCode, value, formatter, new MediaTypeHeaderValue(mediaType));
}
/// <summary>Creates a <see cref="FormattedContentResult{T}"/> with the specified values.</summary>
/// <typeparam name="T">The type of content in the entity body.</typeparam>
/// <param name="statusCode">The HTTP status code for the response message.</param>
/// <param name="value">The content value to format in the entity body.</param>
/// <param name="formatter">The formatter to use to format the content.</param>
/// <param name="mediaType">
/// The value for the Content-Type header, or <see langword="null"/> to have the formatter pick a default
/// value.
/// </param>
/// <returns>A <see cref="FormattedContentResult{T}"/> with the specified values.</returns>
protected internal virtual FormattedContentResult<T> Content<T>(HttpStatusCode statusCode, T value,
MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType)
{
return new FormattedContentResult<T>(statusCode, value, formatter, mediaType, this);
}
/// <summary>
/// Creates a <see cref="CreatedNegotiatedContentResult{T}"/> (201 Created) with the specified values.
/// </summary>
/// <typeparam name="T">The type of content in the entity body.</typeparam>
/// <param name="location">The location at which the content has been created.</param>
/// <param name="content">The content value to negotiate and format in the entity body.</param>
/// <returns>A <see cref="CreatedNegotiatedContentResult{T}"/> with the specified values.</returns>
protected internal CreatedNegotiatedContentResult<T> Created<T>(string location, T content)
{
if (location == null)
{
throw new ArgumentNullException("location");
}
return Created<T>(new Uri(location), content);
}
/// <summary>
/// Creates a <see cref="CreatedNegotiatedContentResult{T}"/> (201 Created) with the specified values.
/// </summary>
/// <typeparam name="T">The type of content in the entity body.</typeparam>
/// <param name="location">The location at which the content has been created.</param>
/// <param name="content">The content value to negotiate and format in the entity body.</param>
/// <returns>A <see cref="CreatedNegotiatedContentResult{T}"/> with the specified values.</returns>
protected internal virtual CreatedNegotiatedContentResult<T> Created<T>(Uri location, T content)
{
return new CreatedNegotiatedContentResult<T>(location, content, this);
}
/// <summary>
/// Creates a <see cref="CreatedAtRouteNegotiatedContentResult{T}"/> (201 Created) with the specified values.
/// </summary>
/// <typeparam name="T">The type of content in the entity body.</typeparam>
/// <param name="routeName">The name of the route to use for generating the URL.</param>
/// <param name="routeValues">The route data to use for generating the URL.</param>
/// <param name="content">The content value to negotiate and format in the entity body.</param>
/// <returns>A <see cref="CreatedAtRouteNegotiatedContentResult{T}"/> with the specified values.</returns>
protected internal CreatedAtRouteNegotiatedContentResult<T> CreatedAtRoute<T>(string routeName,
object routeValues, T content)
{
return CreatedAtRoute<T>(routeName, new HttpRouteValueDictionary(routeValues), content);
}
/// <summary>
/// Creates a <see cref="CreatedAtRouteNegotiatedContentResult{T}"/> (201 Created) with the specified values.
/// </summary>
/// <typeparam name="T">The type of content in the entity body.</typeparam>
/// <param name="routeName">The name of the route to use for generating the URL.</param>
/// <param name="routeValues">The route data to use for generating the URL.</param>
/// <param name="content">The content value to negotiate and format in the entity body.</param>
/// <returns>A <see cref="CreatedAtRouteNegotiatedContentResult{T}"/> with the specified values.</returns>
protected internal virtual CreatedAtRouteNegotiatedContentResult<T> CreatedAtRoute<T>(string routeName,
IDictionary<string, object> routeValues, T content)
{
return new CreatedAtRouteNegotiatedContentResult<T>(routeName, routeValues, content, this);
}
/// <summary>Creates an <see cref="InternalServerErrorResult"/> (500 Internal Server Error).</summary>
/// <returns>A <see cref="InternalServerErrorResult"/>.</returns>
protected internal virtual InternalServerErrorResult InternalServerError()
{
return new InternalServerErrorResult(this);
}
/// <summary>
/// Creates an <see cref="ExceptionResult"/> (500 Internal Server Error) with the specified exception.
/// </summary>
/// <param name="exception">The exception to include in the error.</param>
/// <returns>An <see cref="ExceptionResult"/> with the specified exception.</returns>
protected internal virtual ExceptionResult InternalServerError(Exception exception)
{
return new ExceptionResult(exception, this);
}
/// <summary>Creates a <see cref="JsonResult{T}"/> (200 OK) with the specified value.</summary>
/// <typeparam name="T">The type of content in the entity body.</typeparam>
/// <param name="content">The content value to serialize in the entity body.</param>
/// <returns>A <see cref="JsonResult{T}"/> with the specified value.</returns>
protected internal JsonResult<T> Json<T>(T content)
{
return Json<T>(content, new JsonSerializerSettings());
}
/// <summary>Creates a <see cref="JsonResult{T}"/> (200 OK) with the specified values.</summary>
/// <typeparam name="T">The type of content in the entity body.</typeparam>
/// <param name="content">The content value to serialize in the entity body.</param>
/// <param name="serializerSettings">The serializer settings.</param>
/// <returns>A <see cref="JsonResult{T}"/> with the specified values.</returns>
protected internal JsonResult<T> Json<T>(T content, JsonSerializerSettings serializerSettings)
{
return Json<T>(content, serializerSettings, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false,
throwOnInvalidBytes: true));
}
/// <summary>Creates a <see cref="JsonResult{T}"/> (200 OK) with the specified values.</summary>
/// <typeparam name="T">The type of content in the entity body.</typeparam>
/// <param name="content">The content value to serialize in the entity body.</param>
/// <param name="serializerSettings">The serializer settings.</param>
/// <param name="encoding">The content encoding.</param>
/// <returns>A <see cref="JsonResult{T}"/> with the specified values.</returns>
protected internal virtual JsonResult<T> Json<T>(T content, JsonSerializerSettings serializerSettings,
Encoding encoding)
{
return new JsonResult<T>(content, serializerSettings, encoding, this);
}
/// <summary>Creates a <see cref="NotFoundResult"/> (404 Not Found).</summary>
/// <returns>A <see cref="NotFoundResult"/>.</returns>
protected internal virtual NotFoundResult NotFound()
{
return new NotFoundResult(this);
}
/// <summary>Creates an <see cref="OkResult"/> (200 OK).</summary>
/// <returns>An <see cref="OkResult"/>.</returns>
protected internal virtual OkResult Ok()
{
return new OkResult(this);
}
/// <summary>
/// Creates an <see cref="OkNegotiatedContentResult{T}"/> (200 OK) with the specified values.
/// </summary>
/// <typeparam name="T">The type of content in the entity body.</typeparam>
/// <param name="content">The content value to negotiate and format in the entity body.</param>
/// <returns>An <see cref="OkNegotiatedContentResult{T}"/> with the specified values.</returns>
protected internal virtual OkNegotiatedContentResult<T> Ok<T>(T content)
{
return new OkNegotiatedContentResult<T>(content, this);
}
/// <summary>Creates a <see cref="ResponseMessageResult"/> with the specified response.</summary>
/// <param name="response">The HTTP response message.</param>
/// <returns>A <see cref="ResponseMessageResult"/> for the specified response.</returns>
protected internal virtual ResponseMessageResult ResponseMessage(HttpResponseMessage response)
{
return new ResponseMessageResult(response);
}
/// <summary>Creates a <see cref="StatusCodeResult"/> with the specified status code.</summary>
/// <param name="status">The HTTP status code for the response message</param>
/// <returns>A <see cref="StatusCodeResult"/> with the specified status code.</returns>
protected internal virtual StatusCodeResult StatusCode(HttpStatusCode status)
{
return new StatusCodeResult(status, this);
}
/// <summary>
/// Creates an <see cref="UnauthorizedResult"/> (401 Unauthorized) with the specified values.
/// </summary>
/// <param name="challenges">The WWW-Authenticate challenges.</param>
/// <returns>An <see cref="UnauthorizedResult"/> with the specified values.</returns>
protected internal UnauthorizedResult Unauthorized(params AuthenticationHeaderValue[] challenges)
{
return Unauthorized((IEnumerable<AuthenticationHeaderValue>)challenges);
}
/// <summary>
/// Creates an <see cref="UnauthorizedResult"/> (401 Unauthorized) with the specified values.
/// </summary>
/// <param name="challenges">The WWW-Authenticate challenges.</param>
/// <returns>An <see cref="UnauthorizedResult"/> with the specified values.</returns>
protected internal virtual UnauthorizedResult Unauthorized(IEnumerable<AuthenticationHeaderValue> challenges)
{
return new UnauthorizedResult(challenges, this);
}
protected virtual void Initialize(HttpControllerContext controllerContext)
{
if (controllerContext == null)
{
throw Error.ArgumentNull("controllerContext");
}
_initialized = true;
_controllerContext = controllerContext;
_principalService = Configuration.Services.GetHostPrincipalService();
if (_principalService == null)
{
throw new InvalidOperationException(SRResources.ServicesContainerIHostPrincipalServiceRequired);
}
}
internal static async Task<HttpResponseMessage> InvokeActionWithExceptionFilters(IHttpActionResult innerResult,
HttpActionContext actionContext, CancellationToken cancellationToken, IExceptionFilter[] filters)
{
Contract.Assert(innerResult != null);
Contract.Assert(actionContext != null);
Contract.Assert(filters != null);
Exception exception = null;
try
{
return await innerResult.ExecuteAsync(cancellationToken);
}
catch (Exception e)
{
exception = e;
}
// This code path only runs if the task is faulted with an exception
Contract.Assert(exception != null);
HttpActionExecutedContext executedContext = new HttpActionExecutedContext(actionContext, exception);
// Note: exception filters need to be scheduled in the reverse order so that
// the more specific filter (e.g. Action) executes before the less specific ones (e.g. Global)
for (int i = filters.Length - 1; i >= 0; i--)
{
IExceptionFilter exceptionFilter = filters[i];
await exceptionFilter.ExecuteExceptionFilterAsync(executedContext, cancellationToken);
}
if (executedContext.Response != null)
{
return executedContext.Response;
}
else
{
throw executedContext.Exception;
}
}
#region IDisposable
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!_disposed)
{
_disposed = true;
if (disposing)
{
// TODO: Dispose controller state
}
}
}
#endregion IDisposable
}
}