更新
更旧
// 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.Linq;
using System.Linq.Expressions;
using System.Net;
using System.Net.Sockets;
using System.Numerics;
using System.Reflection;
using System.Reflection.Metadata;
using System.Security.Claims;
using System.Text.Json.Serialization;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Http.Json;
using Microsoft.AspNetCore.Testing;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Xunit;
namespace Microsoft.AspNetCore.Routing.Internal
{
public class RequestDelegateFactoryTests : LoggedTest
public static IEnumerable<object[]> NoResult
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
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?);
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;
}
public void NonStaticTestAction(HttpContext httpContext)
{
httpContext.Items.Add("invoked", _invokedValue);
}
}
[Fact]
public async Task NonStaticMethodInfoOverloadWorksWithBasicReflection()
{
var methodInfo = typeof(TestNonStaticActionClass).GetMethod(
nameof(TestNonStaticActionClass.NonStaticTestAction),
BindingFlags.Public | 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 serviceProvider = new EmptyServiceProvider();
var exNullAction = Assert.Throws<ArgumentNullException>(() => RequestDelegateFactory.Create(action: null!));
var exNullMethodInfo1 = Assert.Throws<ArgumentNullException>(() => RequestDelegateFactory.Create(methodInfo: null!));
Assert.Equal("action", exNullAction.ParamName);
Assert.Equal("methodInfo", exNullMethodInfo1.ParamName);
}
[Fact]
public async Task RequestDelegatePopulatesFromRouteParameterBasedOnParameterName()
{
const string paramName = "value";
const int originalRouteParam = 42;
static void TestAction(HttpContext httpContext, [FromRoute] int value)
{
httpContext.Items.Add("input", value);
}
var httpContext = new DefaultHttpContext();
httpContext.Request.RouteValues[paramName] = originalRouteParam.ToString(NumberFormatInfo.InvariantInfo);
var requestDelegate = RequestDelegateFactory.Create(TestAction);
await requestDelegate(httpContext);
Assert.Equal(originalRouteParam, httpContext.Items["input"]);
private static void TestOptional(HttpContext httpContext, [FromRoute] int value = 42)
{
httpContext.Items.Add("input", value);
}
private static void TestOptionalNullable(HttpContext httpContext, int? value = 42)
{
httpContext.Items.Add("input", value);
}
private static void TestOptionalString(HttpContext httpContext, string value = "default")
httpContext.Items.Add("input", value);
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
[Fact]
public async Task SpecifiedRouteParametersDoNotFallbackToQueryString()
{
var httpContext = new DefaultHttpContext();
var requestDelegate = RequestDelegateFactory.Create((int? id, HttpContext httpContext) =>
{
if (id is not null)
{
httpContext.Items["input"] = id;
}
},
new() { RouteParameterNames = new string[] { "id" } });
httpContext.Request.Query = new QueryCollection(new Dictionary<string, StringValues>
{
["id"] = "42"
});
await requestDelegate(httpContext);
Assert.Null(httpContext.Items["input"]);
}
[Fact]
public async Task CreatingDelegateWithInstanceMethodInfoCreatesInstancePerCall()
{
var methodInfo = typeof(HttpHandler).GetMethod(nameof(HttpHandler.Handle));
Assert.NotNull(methodInfo);
var requestDelegate = RequestDelegateFactory.Create(methodInfo!);
var context = new DefaultHttpContext();
await requestDelegate(context);
Assert.Equal(1, context.Items["calls"]);
await requestDelegate(context);
Assert.Equal(1, context.Items["calls"]);
}
[Fact]
public void SpecifiedEmptyRouteParametersThrowIfRouteParameterDoesNotExist()
{
var ex = Assert.Throws<InvalidOperationException>(() =>
RequestDelegateFactory.Create(([FromRoute] int id) => { }, new() { RouteParameterNames = Array.Empty<string>() }));
Assert.Equal("id is not a route paramter.", ex.Message);
}
[Fact]
public async Task RequestDelegatePopulatesFromRouteOptionalParameter()
var requestDelegate = RequestDelegateFactory.Create(TestOptional);
await requestDelegate(httpContext);
Assert.Equal(42, httpContext.Items["input"]);
}
[Fact]
public async Task RequestDelegatePopulatesFromNullableOptionalParameter()
{
var httpContext = new DefaultHttpContext();
var requestDelegate = RequestDelegateFactory.Create(TestOptional);
await requestDelegate(httpContext);
Assert.Equal(42, httpContext.Items["input"]);
[Fact]
public async Task RequestDelegatePopulatesFromOptionalStringParameter()
{
var httpContext = new DefaultHttpContext();
var requestDelegate = RequestDelegateFactory.Create(TestOptionalString);
await requestDelegate(httpContext);
Assert.Equal("default", httpContext.Items["input"]);
}
[Fact]
public async Task RequestDelegatePopulatesFromRouteOptionalParameterBasedOnParameterName()
{
const string paramName = "value";
const int originalRouteParam = 47;
var httpContext = new DefaultHttpContext();
httpContext.Request.RouteValues[paramName] = originalRouteParam.ToString(NumberFormatInfo.InvariantInfo);
var requestDelegate = RequestDelegateFactory.Create(TestOptional);
Assert.Equal(47, httpContext.Items["input"]);
}
[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(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(TestAction);
await requestDelegate(httpContext);
Assert.Equal(0, deserializedRouteParam);
}
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
public static object?[][] TryParsableParameters
{
get
{
static void Store<T>(HttpContext httpContext, T tryParsable)
{
httpContext.Items["tryParsable"] = tryParsable;
}
var now = DateTime.Now;
return new[]
{
// string is not technically "TryParsable", but it's the special case.
new object[] { (Action<HttpContext, string>)Store, "plain string", "plain string" },
new object[] { (Action<HttpContext, int>)Store, "-42", -42 },
new object[] { (Action<HttpContext, uint>)Store, "42", 42U },
new object[] { (Action<HttpContext, bool>)Store, "true", true },
new object[] { (Action<HttpContext, short>)Store, "-42", (short)-42 },
new object[] { (Action<HttpContext, ushort>)Store, "42", (ushort)42 },
new object[] { (Action<HttpContext, long>)Store, "-42", -42L },
new object[] { (Action<HttpContext, ulong>)Store, "42", 42UL },
new object[] { (Action<HttpContext, IntPtr>)Store, "-42", new IntPtr(-42) },
new object[] { (Action<HttpContext, char>)Store, "A", 'A' },
new object[] { (Action<HttpContext, double>)Store, "0.5", 0.5 },
new object[] { (Action<HttpContext, float>)Store, "0.5", 0.5f },
new object[] { (Action<HttpContext, Half>)Store, "0.5", (Half)0.5f },
new object[] { (Action<HttpContext, decimal>)Store, "0.5", 0.5m },
new object[] { (Action<HttpContext, DateTime>)Store, now.ToString("o"), now },
new object[] { (Action<HttpContext, DateTimeOffset>)Store, "1970-01-01T00:00:00.0000000+00:00", DateTimeOffset.UnixEpoch },
new object[] { (Action<HttpContext, TimeSpan>)Store, "00:00:42", TimeSpan.FromSeconds(42) },
new object[] { (Action<HttpContext, Guid>)Store, "00000000-0000-0000-0000-000000000000", Guid.Empty },
new object[] { (Action<HttpContext, Version>)Store, "6.0.0.42", new Version("6.0.0.42") },
new object[] { (Action<HttpContext, BigInteger>)Store, "-42", new BigInteger(-42) },
new object[] { (Action<HttpContext, IPAddress>)Store, "127.0.0.1", IPAddress.Loopback },
new object[] { (Action<HttpContext, IPEndPoint>)Store, "127.0.0.1:80", new IPEndPoint(IPAddress.Loopback, 80) },
new object[] { (Action<HttpContext, AddressFamily>)Store, "Unix", AddressFamily.Unix },
new object[] { (Action<HttpContext, ILOpCode>)Store, "Nop", ILOpCode.Nop },
new object[] { (Action<HttpContext, AssemblyFlags>)Store, "PublicKey,Retargetable", AssemblyFlags.PublicKey | AssemblyFlags.Retargetable },
new object[] { (Action<HttpContext, int?>)Store, "42", 42 },
new object[] { (Action<HttpContext, MyEnum>)Store, "ValueB", MyEnum.ValueB },
new object[] { (Action<HttpContext, MyTryParsableRecord>)Store, "https://example.org", new MyTryParsableRecord(new Uri("https://example.org")) },
new object?[] { (Action<HttpContext, int>)Store, null, 0 },
new object?[] { (Action<HttpContext, int?>)Store, null, null },
};
}
}
private enum MyEnum { ValueA, ValueB, }
private record MyTryParsableRecord(Uri Uri)
{
public static bool TryParse(string? value, out MyTryParsableRecord? result)
{
if (!Uri.TryCreate(value, UriKind.Absolute, out var uri))
{
result = null;
return false;
}
result = new MyTryParsableRecord(uri);
return true;
}
}
[Theory]
[MemberData(nameof(TryParsableParameters))]
public async Task RequestDelegatePopulatesUnattributedTryParsableParametersFromRouteValue(Delegate action, string? routeValue, object? expectedParameterValue)
{
var httpContext = new DefaultHttpContext();
httpContext.Request.RouteValues["tryParsable"] = routeValue;
var requestDelegate = RequestDelegateFactory.Create(action);
await requestDelegate(httpContext);
Assert.Equal(expectedParameterValue, httpContext.Items["tryParsable"]);
}
[Theory]
[MemberData(nameof(TryParsableParameters))]
public async Task RequestDelegatePopulatesUnattributedTryParsableParametersFromQueryString(Delegate action, string? routeValue, object? expectedParameterValue)
{
var httpContext = new DefaultHttpContext();
httpContext.Request.Query = new QueryCollection(new Dictionary<string, StringValues>
{
["tryParsable"] = routeValue
});
var requestDelegate = RequestDelegateFactory.Create(action);
await requestDelegate(httpContext);
Assert.Equal(expectedParameterValue, httpContext.Items["tryParsable"]);
}
[Fact]
public async Task RequestDelegatePopulatesUnattributedTryParsableParametersFromRouteValueBeforeQueryString()
{
var httpContext = new DefaultHttpContext();
httpContext.Request.RouteValues["tryParsable"] = "42";
httpContext.Request.Query = new QueryCollection(new Dictionary<string, StringValues>
{
["tryParsable"] = "invalid!"
});
var requestDelegate = RequestDelegateFactory.Create((HttpContext httpContext, int tryParsable) =>
httpContext.Items["tryParsable"] = tryParsable;
await requestDelegate(httpContext);
Assert.Equal(42, httpContext.Items["tryParsable"]);
}
public static object[][] DelegatesWithAttributesOnNotTryParsableParameters
{
get
{
void InvalidFromRoute([FromRoute] object notTryParsable) { }
void InvalidFromQuery([FromQuery] object notTryParsable) { }
void InvalidFromHeader([FromHeader] object notTryParsable) { }
return new[]
{
new object[] { (Action<object>)InvalidFromRoute },
new object[] { (Action<object>)InvalidFromQuery },
new object[] { (Action<object>)InvalidFromHeader },
};
}
}
[Theory]
[MemberData(nameof(DelegatesWithAttributesOnNotTryParsableParameters))]
public void CreateThrowsInvalidOperationExceptionWhenAttributeRequiresTryParseMethodThatDoesNotExist(Delegate action)
{
var ex = Assert.Throws<InvalidOperationException>(() => RequestDelegateFactory.Create(action));
Assert.Equal("No public static bool Object.TryParse(string, out Object) method found for notTryParsable.", ex.Message);
}
[Fact]
public void CreateThrowsInvalidOperationExceptionGivenUnnamedArgument()
{
var unnamedParameter = Expression.Parameter(typeof(int));
var lambda = Expression.Lambda(Expression.Block(), unnamedParameter);
var ex = Assert.Throws<InvalidOperationException>(() => RequestDelegateFactory.Create(lambda.Compile()));
Assert.Equal("A parameter does not have a name! Was it generated? All parameters must be named.", ex.Message);
}
[Fact]
public async Task RequestDelegateLogsTryParsableFailuresAsDebugAndSets400Response()
{
var invoked = false;
void TestAction([FromRoute] int tryParsable, [FromRoute] int tryParsable2)
{
invoked = true;
}
var serviceCollection = new ServiceCollection();
serviceCollection.AddSingleton(LoggerFactory);
var httpContext = new DefaultHttpContext();
httpContext.Request.RouteValues["tryParsable"] = "invalid!";
httpContext.Request.RouteValues["tryParsable2"] = "invalid again!";
httpContext.Features.Set<IHttpRequestLifetimeFeature>(new TestHttpRequestLifetimeFeature());
httpContext.RequestServices = serviceCollection.BuildServiceProvider();
var requestDelegate = RequestDelegateFactory.Create(TestAction);
await requestDelegate(httpContext);
Assert.False(invoked);
Assert.False(httpContext.RequestAborted.IsCancellationRequested);
Assert.Equal(400, httpContext.Response.StatusCode);
var logs = TestSink.Writes.ToArray();
Assert.Equal(2, logs.Length);
Assert.Equal(new EventId(3, "ParamaterBindingFailed"), logs[0].EventId);
Assert.Equal(LogLevel.Debug, logs[0].LogLevel);
Assert.Equal(@"Failed to bind parameter ""Int32 tryParsable"" from ""invalid!"".", logs[0].Message);
Assert.Equal(new EventId(3, "ParamaterBindingFailed"), logs[0].EventId);
Assert.Equal(LogLevel.Debug, logs[0].LogLevel);
Assert.Equal(@"Failed to bind parameter ""Int32 tryParsable2"" from ""invalid again!"".", logs[1].Message);
}
[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(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(TestAction);
await requestDelegate(httpContext);
Assert.Equal(originalHeaderParam, deserializedRouteParam);
}
public static object[][] FromBodyActions
void TestExplicitFromBody(HttpContext httpContext, [FromBody] Todo todo)
{
httpContext.Items.Add("body", todo);
}
void TestImpliedFromBody(HttpContext httpContext, Todo myService)
{
httpContext.Items.Add("body", myService);
}
void TestImpliedFromBodyInterface(HttpContext httpContext, ITodo myService)
{
httpContext.Items.Add("body", myService);
}
return new[]
{
new[] { (Action<HttpContext, Todo>)TestExplicitFromBody },
new[] { (Action<HttpContext, Todo>)TestImpliedFromBody },
new[] { (Action<HttpContext, ITodo>)TestImpliedFromBodyInterface },
}
[Theory]
[MemberData(nameof(FromBodyActions))]
public async Task RequestDelegatePopulatesFromBodyParameter(Delegate action)
{
Todo originalTodo = new()
{
Name = "Write more tests!"
};
var httpContext = new DefaultHttpContext();
httpContext.Request.Headers["Content-Type"] = "application/json";
var requestBodyBytes = JsonSerializer.SerializeToUtf8Bytes(originalTodo);
httpContext.Request.Body = new MemoryStream(requestBodyBytes);
var jsonOptions = new JsonOptions();
jsonOptions.SerializerOptions.Converters.Add(new TodoJsonConverter());
var mock = new Mock<IServiceProvider>();
mock.Setup(m => m.GetService(It.IsAny<Type>())).Returns<Type>(t =>
{
if (t == typeof(IOptions<JsonOptions>))
{
return Options.Create(jsonOptions);
}
return null;
});
httpContext.RequestServices = mock.Object;
var requestDelegate = RequestDelegateFactory.Create(action);
var deserializedRequestBody = httpContext.Items["body"];
Assert.Equal(originalTodo.Name, ((Todo)deserializedRequestBody!).Name);
[Theory]
[MemberData(nameof(FromBodyActions))]
public async Task RequestDelegateRejectsEmptyBodyGivenFromBodyParameter(Delegate action)
{
var httpContext = new DefaultHttpContext();
httpContext.Request.Headers["Content-Type"] = "application/json";
httpContext.Request.Headers["Content-Length"] = "0";
var requestDelegate = RequestDelegateFactory.Create(action);
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(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(TestAction);
await requestDelegate(httpContext);
Assert.Equal(default, structToBeZeroed);
}
[Fact]
public async Task RequestDelegateLogsFromBodyIOExceptionsAsDebugAndDoesNotAbort()
{
var invoked = false;
void TestAction([FromBody] Todo todo)
{
invoked = true;
}
var ioException = new IOException();
var serviceCollection = new ServiceCollection();
serviceCollection.AddSingleton(LoggerFactory);
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(TestAction);
await requestDelegate(httpContext);
Assert.False(invoked);
Assert.False(httpContext.RequestAborted.IsCancellationRequested);
var logMessage = Assert.Single(TestSink.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;
void TestAction([FromBody] Todo todo)
{
invoked = true;
}
var invalidDataException = new InvalidDataException();
var serviceCollection = new ServiceCollection();
serviceCollection.AddSingleton(LoggerFactory);
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(TestAction);
await requestDelegate(httpContext);
Assert.False(invoked);
Assert.False(httpContext.RequestAborted.IsCancellationRequested);
Assert.Equal(400, httpContext.Response.StatusCode);
var logMessage = Assert.Single(TestSink.Writes);
Assert.Equal(new EventId(2, "RequestBodyInvalidDataException"), logMessage.EventId);
Assert.Equal(LogLevel.Debug, logMessage.LogLevel);
Assert.Same(invalidDataException, logMessage.Exception);
}
[Fact]
public void BuildRequestDelegateThrowsInvalidOperationExceptionGivenFromBodyOnMultipleParameters()
{
void TestAttributedInvalidAction([FromBody] int value1, [FromBody] int value2) { }
void TestInferredInvalidAction(Todo value1, Todo value2) { }
void TestBothInvalidAction(Todo value1, [FromBody] int value2) { }
Assert.Throws<InvalidOperationException>(() => RequestDelegateFactory.Create(TestAttributedInvalidAction));
Assert.Throws<InvalidOperationException>(() => RequestDelegateFactory.Create(TestInferredInvalidAction));
Assert.Throws<InvalidOperationException>(() => RequestDelegateFactory.Create(TestBothInvalidAction));
public static object[][] FromServiceActions
void TestExplicitFromService(HttpContext httpContext, [FromService] MyService myService)
{
httpContext.Items.Add("service", myService);
}
void TestExplicitFromIEnumerableService(HttpContext httpContext, [FromService] IEnumerable<MyService> myServices)
{
httpContext.Items.Add("service", myServices.Single());
}
void TestImpliedFromService(HttpContext httpContext, IMyService myService)
{
httpContext.Items.Add("service", myService);
}
void TestImpliedIEnumerableFromService(HttpContext httpContext, IEnumerable<MyService> myServices)
{
httpContext.Items.Add("service", myServices.Single());
}
void TestImpliedFromServiceBasedOnContainer(HttpContext httpContext, MyService myService)
{
httpContext.Items.Add("service", myService);
}
return new object[][]
{
new[] { (Action<HttpContext, MyService>)TestExplicitFromService },
new[] { (Action<HttpContext, IEnumerable<MyService>>)TestExplicitFromIEnumerableService },
new[] { (Action<HttpContext, IMyService>)TestImpliedFromService },
new[] { (Action<HttpContext, IEnumerable<MyService>>)TestImpliedIEnumerableFromService },
new[] { (Action<HttpContext, MyService>)TestImpliedFromServiceBasedOnContainer },
}
[Theory]
[MemberData(nameof(FromServiceActions))]
public async Task RequestDelegatePopulatesParametersFromServiceWithAndWithoutAttribute(Delegate action)
{
var myOriginalService = new MyService();
var serviceCollection = new ServiceCollection();
serviceCollection.AddSingleton(myOriginalService);
serviceCollection.AddSingleton<IMyService>(myOriginalService);
var services = serviceCollection.BuildServiceProvider();
using var requestScoped = services.CreateScope();
httpContext.RequestServices = requestScoped.ServiceProvider;
var requestDelegate = RequestDelegateFactory.Create(action, options: new() { ServiceProvider = services });
Assert.Same(myOriginalService, httpContext.Items["service"]);
}
[Theory]
[MemberData(nameof(FromServiceActions))]
public async Task RequestDelegateRequiresServiceForAllFromServiceParameters(Delegate action)
{
var httpContext = new DefaultHttpContext();
httpContext.RequestServices = new EmptyServiceProvider();
var requestDelegate = RequestDelegateFactory.Create(action);
await Assert.ThrowsAsync<InvalidOperationException>(() => requestDelegate(httpContext));
}
[Fact]
public async Task RequestDelegatePopulatesHttpContextParameterWithoutAttribute()
{
HttpContext? httpContextArgument = null;
void TestAction(HttpContext httpContext)
{
httpContextArgument = httpContext;
}
var httpContext = new DefaultHttpContext();
var requestDelegate = RequestDelegateFactory.Create(TestAction);
await requestDelegate(httpContext);
Assert.Same(httpContext, httpContextArgument);
}
public async Task RequestDelegatePassHttpContextRequestAbortedAsCancellationToken()
{
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(TestAction);
await requestDelegate(httpContext);
Assert.Equal(httpContext.RequestAborted, cancellationTokenArgument);
}
[Fact]
public async Task RequestDelegatePassHttpContextUserAsClaimsPrincipal()
{
ClaimsPrincipal? userArgument = null;
void TestAction(ClaimsPrincipal user)
{
userArgument = user;
}
var httpContext = new DefaultHttpContext
{
User = new ClaimsPrincipal()
};
var requestDelegate = RequestDelegateFactory.Create(TestAction);
await requestDelegate(httpContext);
Assert.Equal(httpContext.User, userArgument);
}
[Fact]
public async Task RequestDelegatePassHttpContextRequestAsHttpRequest()
{
HttpRequest? httpRequestArgument = null;
void TestAction(HttpRequest httpRequest)
{
httpRequestArgument = httpRequest;
}
var httpContext = new DefaultHttpContext();
var requestDelegate = RequestDelegateFactory.Create(TestAction);
await requestDelegate(httpContext);
Assert.Equal(httpContext.Request, httpRequestArgument);
}
[Fact]
public async Task RequestDelegatePassesHttpContextRresponseAsHttpResponse()
{
HttpResponse? httpResponseArgument = null;
void TestAction(HttpResponse httpResponse)
{
httpResponseArgument = httpResponse;
}
var httpContext = new DefaultHttpContext();