更新
更旧
// 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.
#nullable enable
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Http.Metadata;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Testing;
using Microsoft.Extensions.Primitives;
using Xunit;
namespace Microsoft.AspNetCore.Routing.Internal
{
public class RequestDelegateFactoryTests
public static IEnumerable<object[]> NoResult
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
void TestAction(HttpContext httpContext)
{
MarkAsInvoked(httpContext);
}
Task TaskTestAction(HttpContext httpContext)
{
MarkAsInvoked(httpContext);
return Task.CompletedTask;
}
ValueTask ValueTaskTestAction(HttpContext httpContext)
{
MarkAsInvoked(httpContext);
return ValueTask.CompletedTask;
}
void StaticTestAction(HttpContext httpContext)
{
MarkAsInvoked(httpContext);
}
Task StaticTaskTestAction(HttpContext httpContext)
{
MarkAsInvoked(httpContext);
return Task.CompletedTask;
}
ValueTask StaticValueTaskTestAction(HttpContext httpContext)
{
MarkAsInvoked(httpContext);
return ValueTask.CompletedTask;
}
void MarkAsInvoked(HttpContext httpContext)
{
httpContext.Items.Add("invoked", true);
}
return new List<object[]>
{
new object[] { (Action<HttpContext>)TestAction },
new object[] { (Func<HttpContext, Task>)TaskTestAction },
new object[] { (Func<HttpContext, ValueTask>)ValueTaskTestAction },
new object[] { (Action<HttpContext>)StaticTestAction },
new object[] { (Func<HttpContext, Task>)StaticTaskTestAction },
new object[] { (Func<HttpContext, ValueTask>)StaticValueTaskTestAction },
};
}
[Theory]
[MemberData(nameof(NoResult))]
public async Task RequestDelegateInvokesAction(Delegate @delegate)
{
var httpContext = new DefaultHttpContext();
var requestDelegate = RequestDelegateFactory.Create(@delegate);
Assert.True(httpContext.Items["invoked"] as bool?);
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
private static void StaticTestActionBasicReflection(HttpContext httpContext)
{
httpContext.Items.Add("invoked", true);
}
[Fact]
public async Task StaticMethodInfoOverloadWorksWithBasicReflection()
{
var methodInfo = typeof(RequestDelegateFactoryTests).GetMethod(
nameof(StaticTestActionBasicReflection),
BindingFlags.NonPublic | BindingFlags.Static,
new[] { typeof(HttpContext) });
var requestDelegate = RequestDelegateFactory.Create(methodInfo!);
var httpContext = new DefaultHttpContext();
await requestDelegate(httpContext);
Assert.True(httpContext.Items["invoked"] as bool?);
}
private class TestNonStaticActionClass
{
private readonly object _invokedValue;
public TestNonStaticActionClass(object invokedValue)
{
_invokedValue = invokedValue;
}
private void NonStaticTestAction(HttpContext httpContext)
{
httpContext.Items.Add("invoked", _invokedValue);
}
}
[Fact]
public async Task NonStaticMethodInfoOverloadWorksWithBasicReflection()
{
var methodInfo = typeof(TestNonStaticActionClass).GetMethod(
"NonStaticTestAction",
BindingFlags.NonPublic | BindingFlags.Instance,
new[] { typeof(HttpContext) });
var invoked = false;
object GetTarget()
{
if (!invoked)
{
invoked = true;
return new TestNonStaticActionClass(1);
}
return new TestNonStaticActionClass(2);
}
var requestDelegate = RequestDelegateFactory.Create(methodInfo!, _ => GetTarget());
var httpContext = new DefaultHttpContext();
await requestDelegate(httpContext);
Assert.Equal(1, httpContext.Items["invoked"]);
httpContext = new DefaultHttpContext();
await requestDelegate(httpContext);
Assert.Equal(2, httpContext.Items["invoked"]);
}
[Fact]
public void BuildRequestDelegateThrowsArgumentNullExceptions()
{
var methodInfo = typeof(RequestDelegateFactoryTests).GetMethod(
nameof(StaticTestActionBasicReflection),
BindingFlags.NonPublic | BindingFlags.Static,
new[] { typeof(HttpContext) });
var exNullAction = Assert.Throws<ArgumentNullException>(() => RequestDelegateFactory.Create(action: null!));
var exNullMethodInfo1 = Assert.Throws<ArgumentNullException>(() => RequestDelegateFactory.Create(methodInfo: null!));
var exNullMethodInfo2 = Assert.Throws<ArgumentNullException>(() => RequestDelegateFactory.Create(methodInfo: null!, _ => 0));
var exNullTargetFactory = Assert.Throws<ArgumentNullException>(() => RequestDelegateFactory.Create(methodInfo!, targetFactory: null!));
Assert.Equal("action", exNullAction.ParamName);
Assert.Equal("methodInfo", exNullMethodInfo1.ParamName);
Assert.Equal("methodInfo", exNullMethodInfo2.ParamName);
Assert.Equal("targetFactory", exNullTargetFactory.ParamName);
}
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
public static IEnumerable<object[]> FromRouteResult
{
get
{
void TestAction(HttpContext httpContext, [FromRoute] int value)
{
StoreInput(httpContext, value);
};
Task TaskTestAction(HttpContext httpContext, [FromRoute] int value)
{
StoreInput(httpContext, value);
return Task.CompletedTask;
}
ValueTask ValueTaskTestAction(HttpContext httpContext, [FromRoute] int value)
{
StoreInput(httpContext, value);
return ValueTask.CompletedTask;
}
return new List<object[]>
{
new object[] { (Action<HttpContext, int>)TestAction },
new object[] { (Func<HttpContext, int, Task>)TaskTestAction },
new object[] { (Func<HttpContext, int, ValueTask>)ValueTaskTestAction },
};
}
}
private static void StoreInput(HttpContext httpContext, object value)
{
httpContext.Items.Add("input", value);
}
[Theory]
[MemberData(nameof(FromRouteResult))]
public async Task RequestDelegatePopulatesFromRouteParameterBasedOnParameterName(Delegate @delegate)
{
const string paramName = "value";
const int originalRouteParam = 42;
var httpContext = new DefaultHttpContext();
httpContext.Request.RouteValues[paramName] = originalRouteParam.ToString(NumberFormatInfo.InvariantInfo);
var requestDelegate = RequestDelegateFactory.Create(@delegate);
await requestDelegate(httpContext);
Assert.Equal(originalRouteParam, httpContext.Items["input"] as int?);
}
public static IEnumerable<object[]> FromRouteOptionalResult
{
get
return new List<object[]>
{
new object[] { (Action<HttpContext, int>)TestAction },
new object[] { (Func<HttpContext, int, Task>)TaskTestAction },
new object[] { (Func<HttpContext, int, ValueTask>)ValueTaskTestAction }
};
}
private static void TestAction(HttpContext httpContext, [FromRoute] int value = 42)
{
StoreInput(httpContext, value);
}
private static Task TaskTestAction(HttpContext httpContext, [FromRoute] int value = 42)
{
StoreInput(httpContext, value);
return Task.CompletedTask;
}
private static ValueTask ValueTaskTestAction(HttpContext httpContext, [FromRoute] int value = 42)
{
StoreInput(httpContext, value);
return ValueTask.CompletedTask;
}
[Theory]
[MemberData(nameof(FromRouteOptionalResult))]
public async Task RequestDelegatePopulatesFromRouteOptionalParameter(Delegate @delegate)
{
var requestDelegate = RequestDelegateFactory.Create(@delegate);
await requestDelegate(httpContext);
Assert.Equal(42, httpContext.Items["input"] as int?);
}
[Theory]
[MemberData(nameof(FromRouteOptionalResult))]
public async Task RequestDelegatePopulatesFromRouteOptionalParameterBasedOnParameterName(Delegate @delegate)
{
const string paramName = "value";
const int originalRouteParam = 47;
var httpContext = new DefaultHttpContext();
httpContext.Request.RouteValues[paramName] = originalRouteParam.ToString(NumberFormatInfo.InvariantInfo);
var requestDelegate = RequestDelegateFactory.Create(@delegate);
Assert.Equal(47, httpContext.Items["input"] as int?);
}
[Fact]
public async Task RequestDelegatePopulatesFromRouteParameterBasedOnAttributeNameProperty()
{
const string specifiedName = "value";
const int originalRouteParam = 42;
int? deserializedRouteParam = null;
void TestAction([FromRoute(Name = specifiedName)] int foo)
{
deserializedRouteParam = foo;
}
var httpContext = new DefaultHttpContext();
httpContext.Request.RouteValues[specifiedName] = originalRouteParam.ToString(NumberFormatInfo.InvariantInfo);
var requestDelegate = RequestDelegateFactory.Create((Action<int>)TestAction);
await requestDelegate(httpContext);
Assert.Equal(originalRouteParam, deserializedRouteParam);
}
[Fact]
public async Task UsesDefaultValueIfNoMatchingRouteValue()
{
const string unmatchedName = "value";
const int unmatchedRouteParam = 42;
int? deserializedRouteParam = null;
void TestAction([FromRoute] int foo)
{
deserializedRouteParam = foo;
}
var httpContext = new DefaultHttpContext();
httpContext.Request.RouteValues[unmatchedName] = unmatchedRouteParam.ToString(NumberFormatInfo.InvariantInfo);
var requestDelegate = RequestDelegateFactory.Create((Action<int>)TestAction);
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
await requestDelegate(httpContext);
Assert.Equal(0, deserializedRouteParam);
}
[Fact]
public async Task RequestDelegatePopulatesFromQueryParameterBasedOnParameterName()
{
const string paramName = "value";
const int originalQueryParam = 42;
int? deserializedRouteParam = null;
void TestAction([FromQuery] int value)
{
deserializedRouteParam = value;
}
var query = new QueryCollection(new Dictionary<string, StringValues>()
{
[paramName] = originalQueryParam.ToString(NumberFormatInfo.InvariantInfo)
});
var httpContext = new DefaultHttpContext();
httpContext.Request.Query = query;
var requestDelegate = RequestDelegateFactory.Create((Action<int>)TestAction);
await requestDelegate(httpContext);
Assert.Equal(originalQueryParam, deserializedRouteParam);
}
[Fact]
public async Task RequestDelegatePopulatesFromHeaderParameterBasedOnParameterName()
{
const string customHeaderName = "X-Custom-Header";
const int originalHeaderParam = 42;
int? deserializedRouteParam = null;
void TestAction([FromHeader(Name = customHeaderName)] int value)
{
deserializedRouteParam = value;
}
var httpContext = new DefaultHttpContext();
httpContext.Request.Headers[customHeaderName] = originalHeaderParam.ToString(NumberFormatInfo.InvariantInfo);
var requestDelegate = RequestDelegateFactory.Create((Action<int>)TestAction);
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
await requestDelegate(httpContext);
Assert.Equal(originalHeaderParam, deserializedRouteParam);
}
[Fact]
public async Task RequestDelegatePopulatesFromBodyParameter()
{
Todo originalTodo = new()
{
Name = "Write more tests!"
};
Todo? deserializedRequestBody = null;
void TestAction([FromBody] Todo todo)
{
deserializedRequestBody = todo;
}
var httpContext = new DefaultHttpContext();
httpContext.Request.Headers["Content-Type"] = "application/json";
var requestBodyBytes = JsonSerializer.SerializeToUtf8Bytes(originalTodo);
httpContext.Request.Body = new MemoryStream(requestBodyBytes);
var requestDelegate = RequestDelegateFactory.Create((Action<Todo>)TestAction);
await requestDelegate(httpContext);
Assert.NotNull(deserializedRequestBody);
Assert.Equal(originalTodo.Name, deserializedRequestBody!.Name);
}
[Fact]
public async Task RequestDelegateRejectsEmptyBodyGivenDefaultFromBodyParameter()
{
void TestAction([FromBody] Todo todo)
{
}
var httpContext = new DefaultHttpContext();
httpContext.Request.Headers["Content-Type"] = "application/json";
httpContext.Request.Headers["Content-Length"] = "0";
var requestDelegate = RequestDelegateFactory.Create((Action<Todo>)TestAction);
await Assert.ThrowsAsync<JsonException>(() => requestDelegate(httpContext));
}
[Fact]
public async Task RequestDelegateAllowsEmptyBodyGivenCorrectyConfiguredFromBodyParameter()
{
var todoToBecomeNull = new Todo();
void TestAction([FromBody(AllowEmpty = true)] Todo todo)
{
todoToBecomeNull = todo;
}
var httpContext = new DefaultHttpContext();
httpContext.Request.Headers["Content-Type"] = "application/json";
httpContext.Request.Headers["Content-Length"] = "0";
var requestDelegate = RequestDelegateFactory.Create((Action<Todo>)TestAction);
await requestDelegate(httpContext);
Assert.Null(todoToBecomeNull);
}
[Fact]
public async Task RequestDelegateAllowsEmptyBodyStructGivenCorrectyConfiguredFromBodyParameter()
{
var structToBeZeroed = new BodyStruct
{
Id = 42
};
void TestAction([FromBody(AllowEmpty = true)] BodyStruct bodyStruct)
{
structToBeZeroed = bodyStruct;
}
var httpContext = new DefaultHttpContext();
httpContext.Request.Headers["Content-Type"] = "application/json";
httpContext.Request.Headers["Content-Length"] = "0";
var requestDelegate = RequestDelegateFactory.Create((Action<BodyStruct>)TestAction);
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
await requestDelegate(httpContext);
Assert.Equal(default, structToBeZeroed);
}
[Fact]
public async Task RequestDelegateLogsFromBodyIOExceptionsAsDebugAndAborts()
{
var invoked = false;
var sink = new TestSink(context => context.LoggerName == "Microsoft.AspNetCore.Routing.MapAction");
var testLoggerFactory = new TestLoggerFactory(sink, enabled: true);
void TestAction([FromBody] Todo todo)
{
invoked = true;
}
var ioException = new IOException();
var serviceCollection = new ServiceCollection();
serviceCollection.AddSingleton<ILoggerFactory>(testLoggerFactory);
var httpContext = new DefaultHttpContext();
httpContext.Request.Headers["Content-Type"] = "application/json";
httpContext.Request.Body = new IOExceptionThrowingRequestBodyStream(ioException);
httpContext.Features.Set<IHttpRequestLifetimeFeature>(new TestHttpRequestLifetimeFeature());
httpContext.RequestServices = serviceCollection.BuildServiceProvider();
var requestDelegate = RequestDelegateFactory.Create((Action<Todo>)TestAction);
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
await requestDelegate(httpContext);
Assert.False(invoked);
Assert.True(httpContext.RequestAborted.IsCancellationRequested);
var logMessage = Assert.Single(sink.Writes);
Assert.Equal(new EventId(1, "RequestBodyIOException"), logMessage.EventId);
Assert.Equal(LogLevel.Debug, logMessage.LogLevel);
Assert.Same(ioException, logMessage.Exception);
}
[Fact]
public async Task RequestDelegateLogsFromBodyInvalidDataExceptionsAsDebugAndSets400Response()
{
var invoked = false;
var sink = new TestSink(context => context.LoggerName == "Microsoft.AspNetCore.Routing.MapAction");
var testLoggerFactory = new TestLoggerFactory(sink, enabled: true);
void TestAction([FromBody] Todo todo)
{
invoked = true;
}
var invalidDataException = new InvalidDataException();
var serviceCollection = new ServiceCollection();
serviceCollection.AddSingleton<ILoggerFactory>(testLoggerFactory);
var httpContext = new DefaultHttpContext();
httpContext.Request.Headers["Content-Type"] = "application/json";
httpContext.Request.Body = new IOExceptionThrowingRequestBodyStream(invalidDataException);
httpContext.Features.Set<IHttpRequestLifetimeFeature>(new TestHttpRequestLifetimeFeature());
httpContext.RequestServices = serviceCollection.BuildServiceProvider();
var requestDelegate = RequestDelegateFactory.Create((Action<Todo>)TestAction);
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
await requestDelegate(httpContext);
Assert.False(invoked);
Assert.False(httpContext.RequestAborted.IsCancellationRequested);
Assert.Equal(400, httpContext.Response.StatusCode);
var logMessage = Assert.Single(sink.Writes);
Assert.Equal(new EventId(2, "RequestBodyInvalidDataException"), logMessage.EventId);
Assert.Equal(LogLevel.Debug, logMessage.LogLevel);
Assert.Same(invalidDataException, logMessage.Exception);
}
[Fact]
public async Task RequestDelegatePopulatesFromFormParameterBasedOnParameterName()
{
const string paramName = "value";
const int originalQueryParam = 42;
int? deserializedRouteParam = null;
void TestAction([FromForm] int value)
{
deserializedRouteParam = value;
}
var form = new FormCollection(new Dictionary<string, StringValues>()
{
[paramName] = originalQueryParam.ToString(NumberFormatInfo.InvariantInfo)
});
var httpContext = new DefaultHttpContext();
httpContext.Request.Form = form;
var requestDelegate = RequestDelegateFactory.Create((Action<int>)TestAction);
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
await requestDelegate(httpContext);
Assert.Equal(originalQueryParam, deserializedRouteParam);
}
[Fact]
public async Task RequestDelegateLogsFromFormIOExceptionsAsDebugAndAborts()
{
var invoked = false;
var sink = new TestSink(context => context.LoggerName == "Microsoft.AspNetCore.Routing.MapAction");
var testLoggerFactory = new TestLoggerFactory(sink, enabled: true);
void TestAction([FromForm] int value)
{
invoked = true;
}
var ioException = new IOException();
var serviceCollection = new ServiceCollection();
serviceCollection.AddSingleton<ILoggerFactory>(testLoggerFactory);
var httpContext = new DefaultHttpContext();
httpContext.Request.Headers["Content-Type"] = "application/x-www-form-urlencoded";
httpContext.Request.Body = new IOExceptionThrowingRequestBodyStream(ioException);
httpContext.Features.Set<IHttpRequestLifetimeFeature>(new TestHttpRequestLifetimeFeature());
httpContext.RequestServices = serviceCollection.BuildServiceProvider();
var requestDelegate = RequestDelegateFactory.Create((Action<int>)TestAction);
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
await requestDelegate(httpContext);
Assert.False(invoked);
Assert.True(httpContext.RequestAborted.IsCancellationRequested);
var logMessage = Assert.Single(sink.Writes);
Assert.Equal(new EventId(1, "RequestBodyIOException"), logMessage.EventId);
Assert.Equal(LogLevel.Debug, logMessage.LogLevel);
Assert.Same(ioException, logMessage.Exception);
}
[Fact]
public async Task RequestDelegateLogsFromFormInvalidDataExceptionsAsDebugAndSets400Response()
{
var invoked = false;
var sink = new TestSink(context => context.LoggerName == "Microsoft.AspNetCore.Routing.MapAction");
var testLoggerFactory = new TestLoggerFactory(sink, enabled: true);
void TestAction([FromForm] int value)
{
invoked = true;
}
var invalidDataException = new InvalidDataException();
var serviceCollection = new ServiceCollection();
serviceCollection.AddSingleton<ILoggerFactory>(testLoggerFactory);
var httpContext = new DefaultHttpContext();
httpContext.Request.Headers["Content-Type"] = "application/x-www-form-urlencoded";
httpContext.Request.Body = new IOExceptionThrowingRequestBodyStream(invalidDataException);
httpContext.Features.Set<IHttpRequestLifetimeFeature>(new TestHttpRequestLifetimeFeature());
httpContext.RequestServices = serviceCollection.BuildServiceProvider();
var requestDelegate = RequestDelegateFactory.Create((Action<int>)TestAction);
await requestDelegate(httpContext);
Assert.False(invoked);
Assert.False(httpContext.RequestAborted.IsCancellationRequested);
Assert.Equal(400, httpContext.Response.StatusCode);
var logMessage = Assert.Single(sink.Writes);
Assert.Equal(new EventId(2, "RequestBodyInvalidDataException"), logMessage.EventId);
Assert.Equal(LogLevel.Debug, logMessage.LogLevel);
Assert.Same(invalidDataException, logMessage.Exception);
}
[Fact]
public void BuildRequestDelegateThrowsInvalidOperationExceptionGivenBothFromBodyAndFromFormOnDifferentParameters()
{
void TestAction([FromBody] int value1, [FromForm] int value2) { }
void TestActionWithFlippedParams([FromForm] int value1, [FromBody] int value2) { }
Assert.Throws<InvalidOperationException>(() => RequestDelegateFactory.Create((Action<int, int>)TestAction));
Assert.Throws<InvalidOperationException>(() => RequestDelegateFactory.Create((Action<int, int>)TestActionWithFlippedParams));
}
[Fact]
public void BuildRequestDelegateThrowsInvalidOperationExceptionGivenFromBodyOnMultipleParameters()
{
void TestAction([FromBody] int value1, [FromBody] int value2) { }
Assert.Throws<InvalidOperationException>(() => RequestDelegateFactory.Create((Action<int, int>)TestAction));
}
[Fact]
public async Task RequestDelegatePopulatesFromServiceParameterBasedOnParameterType()
{
var myOriginalService = new MyService();
MyService? injectedService = null;
void TestAction([FromService] MyService myService)
{
injectedService = myService;
}
var serviceCollection = new ServiceCollection();
serviceCollection.AddSingleton(myOriginalService);
var httpContext = new DefaultHttpContext();
httpContext.RequestServices = serviceCollection.BuildServiceProvider();
var requestDelegate = RequestDelegateFactory.Create((Action<MyService>)TestAction);
await requestDelegate(httpContext);
Assert.Same(myOriginalService, injectedService);
}
[Fact]
public async Task RequestDelegatePopulatesHttpContextParameterWithoutAttribute()
{
HttpContext? httpContextArgument = null;
void TestAction(HttpContext httpContext)
{
httpContextArgument = httpContext;
}
var httpContext = new DefaultHttpContext();
var requestDelegate = RequestDelegateFactory.Create((Action<HttpContext>)TestAction);
await requestDelegate(httpContext);
Assert.Same(httpContext, httpContextArgument);
}
[Fact]
public async Task RequestDelegatePopulatesIFormCollectionParameterWithoutAttribute()
{
IFormCollection? formCollectionArgument = null;
void TestAction(IFormCollection httpContext)
{
formCollectionArgument = httpContext;
}
var httpContext = new DefaultHttpContext();
httpContext.Request.Headers["Content-Type"] = "application/x-www-form-urlencoded";
var requestDelegate = RequestDelegateFactory.Create((Action<IFormCollection>)TestAction);
await requestDelegate(httpContext);
Assert.Same(httpContext.Request.Form, formCollectionArgument);
}
[Fact]
public async Task RequestDelegatePassHttpContextRequestAbortedAsCancelationToken()
{
CancellationToken? cancellationTokenArgument = null;
void TestAction(CancellationToken cancellationToken)
{
cancellationTokenArgument = cancellationToken;
}
using var cts = new CancellationTokenSource();
var httpContext = new DefaultHttpContext
{
RequestAborted = cts.Token
};
var requestDelegate = RequestDelegateFactory.Create((Action<CancellationToken>)TestAction);
await requestDelegate(httpContext);
Assert.Equal(httpContext.RequestAborted, cancellationTokenArgument);
}
public static IEnumerable<object[]> ComplexResult
Todo originalTodo = new()
{
Name = "Write even more tests!"
};
Todo TestAction() => originalTodo;
Task<Todo> TaskTestAction() => Task.FromResult(originalTodo);
ValueTask<Todo> ValueTaskTestAction() => ValueTask.FromResult(originalTodo);
static Todo StaticTestAction() => new Todo { Name = "Write even more tests!" };
static Task<Todo> StaticTaskTestAction() => Task.FromResult(new Todo { Name = "Write even more tests!" });
static ValueTask<Todo> StaticValueTaskTestAction() => ValueTask.FromResult(new Todo { Name = "Write even more tests!" });
return new List<object[]>
{
new object[] { (Func<Todo>)TestAction },
new object[] { (Func<Task<Todo>>)TaskTestAction},
new object[] { (Func<ValueTask<Todo>>)ValueTaskTestAction},
new object[] { (Func<Todo>)StaticTestAction},
new object[] { (Func<Task<Todo>>)StaticTaskTestAction},
new object[] { (Func<ValueTask<Todo>>)StaticValueTaskTestAction},
};
}
}
[Theory]
[MemberData(nameof(ComplexResult))]
public async Task RequestDelegateWritesComplexReturnValueAsJsonResponseBody(Delegate @delegate)
{
var httpContext = new DefaultHttpContext();
var responseBodyStream = new MemoryStream();
httpContext.Response.Body = responseBodyStream;
var requestDelegate = RequestDelegateFactory.Create(@delegate);
await requestDelegate(httpContext);
var deserializedResponseBody = JsonSerializer.Deserialize<Todo>(responseBodyStream.ToArray(), new JsonSerializerOptions
{
// TODO: the output is "{\"id\":0,\"name\":\"Write even more tests!\",\"isComplete\":false}"
// Verify that the camelCased property names are consistent with MVC and if so whether we should keep the behavior.
PropertyNameCaseInsensitive = true
});
Assert.NotNull(deserializedResponseBody);
Assert.Equal("Write even more tests!", deserializedResponseBody!.Name);
public static IEnumerable<object[]> CustomResults
get
{
var resultString = "Still not enough tests!";
CustomResult TestAction() => new CustomResult(resultString);
Task<CustomResult> TaskTestAction() => Task.FromResult(new CustomResult(resultString));
ValueTask<CustomResult> ValueTaskTestAction() => ValueTask.FromResult(new CustomResult(resultString));
static CustomResult StaticTestAction() => new CustomResult("Still not enough tests!");
static Task<CustomResult> StaticTaskTestAction() => Task.FromResult(new CustomResult("Still not enough tests!"));
static ValueTask<CustomResult> StaticValueTaskTestAction() => ValueTask.FromResult(new CustomResult("Still not enough tests!"));
return new List<object[]>
{
new object[] { (Func<CustomResult>)TestAction },
new object[] { (Func<Task<CustomResult>>)TaskTestAction},
new object[] { (Func<ValueTask<CustomResult>>)ValueTaskTestAction},
new object[] { (Func<CustomResult>)StaticTestAction},
new object[] { (Func<Task<CustomResult>>)StaticTaskTestAction},
new object[] { (Func<ValueTask<CustomResult>>)StaticValueTaskTestAction},
};
}
}
[Theory]
[MemberData(nameof(CustomResults))]
public async Task RequestDelegateUsesCustomIResult(Delegate @delegate)
{
var httpContext = new DefaultHttpContext();
var responseBodyStream = new MemoryStream();
httpContext.Response.Body = responseBodyStream;
var requestDelegate = RequestDelegateFactory.Create(@delegate);
await requestDelegate(httpContext);
var decodedResponseBody = Encoding.UTF8.GetString(responseBodyStream.ToArray());
Assert.Equal("Still not enough tests!", decodedResponseBody);
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
public static IEnumerable<object[]> StringResult
{
get
{
var test = "String Test";
string TestAction() => test;
Task<string> TaskTestAction() => Task.FromResult(test);
ValueTask<string> ValueTaskTestAction() => ValueTask.FromResult(test);
static string StaticTestAction() => "String Test";
static Task<string> StaticTaskTestAction() => Task.FromResult("String Test");
static ValueTask<string> StaticValueTaskTestAction() => ValueTask.FromResult("String Test");
return new List<object[]>
{
new object[] { (Func<string>)TestAction },
new object[] { (Func<Task<string>>)TaskTestAction },
new object[] { (Func<ValueTask<string>>)ValueTaskTestAction },
new object[] { (Func<string>)StaticTestAction },
new object[] { (Func<Task<string>>)StaticTaskTestAction },
new object[] { (Func<ValueTask<string>>)StaticValueTaskTestAction },
};
}
}
[Theory]
[MemberData(nameof(StringResult))]
public async Task RequestDelegateWritesStringReturnValueAsJsonResponseBody(Delegate @delegate)
{
var httpContext = new DefaultHttpContext();
var responseBodyStream = new MemoryStream();
httpContext.Response.Body = responseBodyStream;
var requestDelegate = RequestDelegateFactory.Create(@delegate);
await requestDelegate(httpContext);
var responseBody = Encoding.UTF8.GetString(responseBodyStream.ToArray());
Assert.Equal("String Test", responseBody);
}
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
public static IEnumerable<object[]> IntResult
{
get
{
int TestAction() => 42;
Task<int> TaskTestAction() => Task.FromResult(42);
ValueTask<int> ValueTaskTestAction() => ValueTask.FromResult(42);
static int StaticTestAction() => 42;
static Task<int> StaticTaskTestAction() => Task.FromResult(42);
static ValueTask<int> StaticValueTaskTestAction() => ValueTask.FromResult(42);
return new List<object[]>
{
new object[] { (Func<int>)TestAction },
new object[] { (Func<Task<int>>)TaskTestAction },
new object[] { (Func<ValueTask<int>>)ValueTaskTestAction },
new object[] { (Func<int>)StaticTestAction },
new object[] { (Func<Task<int>>)StaticTaskTestAction },
new object[] { (Func<ValueTask<int>>)StaticValueTaskTestAction },
};
}
}
[Theory]
[MemberData(nameof(IntResult))]
public async Task RequestDelegateWritesIntReturnValue(Delegate @delegate)
{
var httpContext = new DefaultHttpContext();
var responseBodyStream = new MemoryStream();
httpContext.Response.Body = responseBodyStream;
var requestDelegate = RequestDelegateFactory.Create(@delegate);
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
await requestDelegate(httpContext);
var responseBody = Encoding.UTF8.GetString(responseBodyStream.ToArray());
Assert.Equal("42", responseBody);
}
public static IEnumerable<object[]> BoolResult
{
get
{
bool TestAction() => true;
Task<bool> TaskTestAction() => Task.FromResult(true);
ValueTask<bool> ValueTaskTestAction() => ValueTask.FromResult(true);
static bool StaticTestAction() => true;
static Task<bool> StaticTaskTestAction() => Task.FromResult(true);
static ValueTask<bool> StaticValueTaskTestAction() => ValueTask.FromResult(true);
return new List<object[]>
{
new object[] { (Func<bool>)TestAction },
new object[] { (Func<Task<bool>>)TaskTestAction },
new object[] { (Func<ValueTask<bool>>)ValueTaskTestAction },
new object[] { (Func<bool>)StaticTestAction },
new object[] { (Func<Task<bool>>)StaticTaskTestAction },
new object[] { (Func<ValueTask<bool>>)StaticValueTaskTestAction },
};
}
}
[Theory]
[MemberData(nameof(BoolResult))]
public async Task RequestDelegateWritesBoolReturnValue(Delegate @delegate)
{
var httpContext = new DefaultHttpContext();
var responseBodyStream = new MemoryStream();
httpContext.Response.Body = responseBodyStream;
var requestDelegate = RequestDelegateFactory.Create(@delegate);
await requestDelegate(httpContext);
var responseBody = Encoding.UTF8.GetString(responseBodyStream.ToArray());
Assert.Equal("true", responseBody);
}
private class Todo
{
public int Id { get; set; }
public string? Name { get; set; } = "Todo";
public bool IsComplete { get; set; }
}
private struct BodyStruct
{
public int Id { get; set; }
}
private class FromRouteAttribute : Attribute, IFromRouteMetadata
{
public string? Name { get; set; }
}