diff --git a/src/Components/WebAssembly/DevServer/src/Server/Startup.cs b/src/Components/WebAssembly/DevServer/src/Server/Startup.cs index 2541597dca4e..418d062dc597 100644 --- a/src/Components/WebAssembly/DevServer/src/Server/Startup.cs +++ b/src/Components/WebAssembly/DevServer/src/Server/Startup.cs @@ -58,7 +58,7 @@ private static void EnableConfiguredPathbase(IApplicationBuilder app, IConfigura { if (context.Request.PathBase == pathBase) { - return next(); + return next(context); } else { diff --git a/src/Components/WebAssembly/Server/src/ComponentsWebAssemblyApplicationBuilderExtensions.cs b/src/Components/WebAssembly/Server/src/ComponentsWebAssemblyApplicationBuilderExtensions.cs index f6fa4e04f5e8..fedf3d437dcf 100644 --- a/src/Components/WebAssembly/Server/src/ComponentsWebAssemblyApplicationBuilderExtensions.cs +++ b/src/Components/WebAssembly/Server/src/ComponentsWebAssemblyApplicationBuilderExtensions.cs @@ -56,7 +56,7 @@ public static IApplicationBuilder UseBlazorFrameworkFiles(this IApplicationBuild context.Response.Headers.Append("DOTNET-MODIFIABLE-ASSEMBLIES", Environment.GetEnvironmentVariable("DOTNET_MODIFIABLE_ASSEMBLIES")); } - await next(); + await next(context); }); subBuilder.UseMiddleware(); diff --git a/src/Components/WebAssembly/Server/src/WebAssemblyNetDebugProxyAppBuilderExtensions.cs b/src/Components/WebAssembly/Server/src/WebAssemblyNetDebugProxyAppBuilderExtensions.cs index fc96d8d7006c..123df48a4be7 100644 --- a/src/Components/WebAssembly/Server/src/WebAssemblyNetDebugProxyAppBuilderExtensions.cs +++ b/src/Components/WebAssembly/Server/src/WebAssemblyNetDebugProxyAppBuilderExtensions.cs @@ -21,7 +21,7 @@ public static void UseWebAssemblyDebugging(this IApplicationBuilder app) { app.Map("/_framework/debug", app => { - app.Use(async (context, next) => + app.Run(async (context) => { var queryParams = HttpUtility.ParseQueryString(context.Request.QueryString.Value!); var browserParam = queryParams.Get("browser"); diff --git a/src/Components/WebAssembly/testassets/HostedInAspNet.Server/Startup.cs b/src/Components/WebAssembly/testassets/HostedInAspNet.Server/Startup.cs index 2cafccc6b593..6698a990db95 100644 --- a/src/Components/WebAssembly/testassets/HostedInAspNet.Server/Startup.cs +++ b/src/Components/WebAssembly/testassets/HostedInAspNet.Server/Startup.cs @@ -41,7 +41,7 @@ public void Configure(IApplicationBuilder app, IWebHostEnvironment env, BootReso { bootResourceRequestLog.AddRequest(context.Request); } - return next(); + return next(context); }); if (env.IsDevelopment()) diff --git a/src/Components/test/testassets/TestServer/ServerStartup.cs b/src/Components/test/testassets/TestServer/ServerStartup.cs index 16eb89fa4f6f..4c68c4a23820 100644 --- a/src/Components/test/testassets/TestServer/ServerStartup.cs +++ b/src/Components/test/testassets/TestServer/ServerStartup.cs @@ -47,7 +47,7 @@ public void Configure(IApplicationBuilder app, IWebHostEnvironment env, Resource resourceRequestLog.AddRequest(context.Request); } - return next(); + return next(context); }); app.UseStaticFiles(); diff --git a/src/Hosting/TestHost/test/TestServerTests.cs b/src/Hosting/TestHost/test/TestServerTests.cs index 06e95f90dbe1..7717ae8006b0 100644 --- a/src/Hosting/TestHost/test/TestServerTests.cs +++ b/src/Hosting/TestHost/test/TestServerTests.cs @@ -150,7 +150,7 @@ public void ConfigureContainer(ThirdPartyContainer container) => container.Services.AddSingleton(new TestService { Message = "ConfigureContainer" }); public void Configure(IApplicationBuilder app) => - app.Use((ctx, next) => ctx.Response.WriteAsync( + app.Run(ctx => ctx.Response.WriteAsync( $"{ctx.RequestServices.GetRequiredService().Message}, {ctx.RequestServices.GetRequiredService().Message}")); } @@ -472,7 +472,7 @@ public Action Configure(Action next) app.Use(async (context, nxt) => { context.Features.Set(this); - await nxt(); + await nxt(context); }); next(app); }; @@ -514,7 +514,7 @@ public Action Configure(Action next) app.Use(async (context, nxt) => { context.Features.Set(this); - await nxt(); + await nxt(context); }); next(app); }; diff --git a/src/Http/Http.Abstractions/src/Extensions/UseExtensions.cs b/src/Http/Http.Abstractions/src/Extensions/UseExtensions.cs index c0c9a0f6e50c..a16093337c48 100644 --- a/src/Http/Http.Abstractions/src/Extensions/UseExtensions.cs +++ b/src/Http/Http.Abstractions/src/Extensions/UseExtensions.cs @@ -14,9 +14,19 @@ public static class UseExtensions { /// /// Adds a middleware delegate defined in-line to the application's request pipeline. + /// If you aren't calling the next function, use instead. + /// + /// Prefer using for better performance as shown below: + /// + /// app.Use((context, next) => + /// { + /// return next(context); + /// }); + /// + /// /// /// The instance. - /// A function that handles the request or calls the given next function. + /// A function that handles the request and calls the given next function. /// The instance. public static IApplicationBuilder Use(this IApplicationBuilder app, Func, Task> middleware) { @@ -29,5 +39,17 @@ public static IApplicationBuilder Use(this IApplicationBuilder app, Func + /// Adds a middleware delegate defined in-line to the application's request pipeline. + /// If you aren't calling the next function, use instead. + /// + /// The instance. + /// A function that handles the request and calls the given next function. + /// The instance. + public static IApplicationBuilder Use(this IApplicationBuilder app, Func middleware) + { + return app.Use(next => context => middleware(context, next)); + } } } diff --git a/src/Http/Http.Abstractions/src/PublicAPI.Unshipped.txt b/src/Http/Http.Abstractions/src/PublicAPI.Unshipped.txt index 4ff4474b6bf7..0676a6f9f794 100644 --- a/src/Http/Http.Abstractions/src/PublicAPI.Unshipped.txt +++ b/src/Http/Http.Abstractions/src/PublicAPI.Unshipped.txt @@ -18,5 +18,6 @@ Microsoft.AspNetCore.Http.Metadata.IFromServiceMetadata Microsoft.AspNetCore.Http.Endpoint.Endpoint(Microsoft.AspNetCore.Http.RequestDelegate? requestDelegate, Microsoft.AspNetCore.Http.EndpointMetadataCollection? metadata, string? displayName) -> void Microsoft.AspNetCore.Http.Endpoint.RequestDelegate.get -> Microsoft.AspNetCore.Http.RequestDelegate? Microsoft.AspNetCore.Routing.RouteValueDictionary.TryAdd(string! key, object? value) -> bool +static Microsoft.AspNetCore.Builder.UseExtensions.Use(this Microsoft.AspNetCore.Builder.IApplicationBuilder! app, System.Func! middleware) -> Microsoft.AspNetCore.Builder.IApplicationBuilder! static Microsoft.AspNetCore.Builder.UseMiddlewareExtensions.UseMiddleware(this Microsoft.AspNetCore.Builder.IApplicationBuilder! app, System.Type! middleware, params object?[]! args) -> Microsoft.AspNetCore.Builder.IApplicationBuilder! static Microsoft.AspNetCore.Builder.UseMiddlewareExtensions.UseMiddleware(this Microsoft.AspNetCore.Builder.IApplicationBuilder! app, params object?[]! args) -> Microsoft.AspNetCore.Builder.IApplicationBuilder! diff --git a/src/Http/Http.Abstractions/test/UseExtensionsTests.cs b/src/Http/Http.Abstractions/test/UseExtensionsTests.cs new file mode 100644 index 000000000000..559a6149ecbc --- /dev/null +++ b/src/Http/Http.Abstractions/test/UseExtensionsTests.cs @@ -0,0 +1,80 @@ +// 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; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Http; +using Xunit; + +namespace Microsoft.AspNetCore.Builder.Extensions +{ + public class UseExtensionsTests + { + [Fact] + public async Task UseCallsNextMiddleware() + { + // Arrange + var builder = new ApplicationBuilder(serviceProvider: null!); + var context = new DefaultHttpContext(); + var firstCalled = false; + var secondCalled = false; + var lastCalled = false; + + builder.Use((context, next) => + { + firstCalled = true; + return next(); + }); + builder.Use((context, next) => + { + Assert.True(firstCalled); + secondCalled = true; + return next(context); + }); + builder.Run(context => + { + Assert.True(secondCalled); + lastCalled = true; + return Task.CompletedTask; + }); + + // Act + await builder.Build().Invoke(context); + + // Assert + Assert.True(firstCalled); + Assert.True(secondCalled); + Assert.True(lastCalled); + } + + [Fact] + public async Task ThrowFromMiddlewareFlowsBackToInvoke() + { + // Arrange + var builder = new ApplicationBuilder(serviceProvider: null!); + var context = new DefaultHttpContext(); + var shouldThrow = true; + + builder.Use(async (context, next) => + { + throw await Assert.ThrowsAsync(() => next()); + }); + builder.Use(async (context, next) => + { + throw await Assert.ThrowsAsync(() => next(context)); + }); + builder.Run(context => + { + if (shouldThrow) + { + throw new Exception("From Use"); + } + return Task.CompletedTask; + }); + + // Act & Assert + var ex = await Assert.ThrowsAsync(() => builder.Build().Invoke(context)); + Assert.Equal("From Use", ex.Message); + } + } +} diff --git a/src/Http/Http/test/ApplicationBuilderTests.cs b/src/Http/Http/test/ApplicationBuilderTests.cs index 7e3c7f80c005..215e4b920b3e 100644 --- a/src/Http/Http/test/ApplicationBuilderTests.cs +++ b/src/Http/Http/test/ApplicationBuilderTests.cs @@ -55,7 +55,7 @@ public async Task BuildImplicitlyThrowsForMatchedEndpointAsLastStep() public void BuildDoesNotCallMatchedEndpointWhenTerminated() { var builder = new ApplicationBuilder(null); - builder.Use((context, next) => + builder.Run(context => { // Do not call next return Task.CompletedTask; diff --git a/src/Http/Routing/test/testassets/RoutingSandbox/UseRouterStartup.cs b/src/Http/Routing/test/testassets/RoutingSandbox/UseRouterStartup.cs index d7ae4709890b..e42208d85010 100644 --- a/src/Http/Routing/test/testassets/RoutingSandbox/UseRouterStartup.cs +++ b/src/Http/Routing/test/testassets/RoutingSandbox/UseRouterStartup.cs @@ -1,4 +1,4 @@ -// Copyright (c) .NET Foundation. All rights reserved. +// 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; @@ -31,7 +31,7 @@ public void Configure(IApplicationBuilder app) }); routes.MapGet("api/get/{id}", (request, response, routeData) => response.WriteAsync($"API Get {routeData.Values["id"]}")) - .MapMiddlewareRoute("api/middleware", (appBuilder) => appBuilder.Use((httpContext, next) => httpContext.Response.WriteAsync("Middleware!"))) + .MapMiddlewareRoute("api/middleware", (appBuilder) => appBuilder.Run(httpContext => httpContext.Response.WriteAsync("Middleware!"))) .MapRoute( name: "AllVerbs", template: "api/all/{name}/{lastName?}", diff --git a/src/Http/Routing/test/testassets/RoutingWebSite/UseRouterStartup.cs b/src/Http/Routing/test/testassets/RoutingWebSite/UseRouterStartup.cs index f09f359acfe5..9ce84fe6f61e 100644 --- a/src/Http/Routing/test/testassets/RoutingWebSite/UseRouterStartup.cs +++ b/src/Http/Routing/test/testassets/RoutingWebSite/UseRouterStartup.cs @@ -1,4 +1,4 @@ -// Copyright (c) .NET Foundation. All rights reserved. +// 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; @@ -31,7 +31,7 @@ public void Configure(IApplicationBuilder app) }); routes.MapGet("api/get/{id}", (request, response, routeData) => response.WriteAsync($"API Get {routeData.Values["id"]}")) - .MapMiddlewareRoute("api/middleware", (appBuilder) => appBuilder.Use((httpContext, next) => httpContext.Response.WriteAsync("Middleware!"))) + .MapMiddlewareRoute("api/middleware", (appBuilder) => appBuilder.Run(httpContext => httpContext.Response.WriteAsync("Middleware!"))) .MapRoute( name: "AllVerbs", template: "api/all/{name}/{lastName?}", diff --git a/src/Identity/test/InMemory.Test/FunctionalTest.cs b/src/Identity/test/InMemory.Test/FunctionalTest.cs index b651e656c7b3..ededc2b7172f 100644 --- a/src/Identity/test/InMemory.Test/FunctionalTest.cs +++ b/src/Identity/test/InMemory.Test/FunctionalTest.cs @@ -368,7 +368,7 @@ private static async Task CreateServer(Action co } else { - await next(); + await next(context); } }); }) diff --git a/src/Middleware/CORS/test/UnitTests/CorsMiddlewareTests.cs b/src/Middleware/CORS/test/UnitTests/CorsMiddlewareTests.cs index bf4848307a41..2abb1ae60a14 100644 --- a/src/Middleware/CORS/test/UnitTests/CorsMiddlewareTests.cs +++ b/src/Middleware/CORS/test/UnitTests/CorsMiddlewareTests.cs @@ -584,7 +584,7 @@ public async Task CorsRequest_SetsResponseHeader_IfExceptionHandlerClearsRespons { try { - await next(); + await next(context); } catch (Exception) { diff --git a/src/Middleware/Diagnostics/test/UnitTests/ExceptionHandlerTest.cs b/src/Middleware/Diagnostics/test/UnitTests/ExceptionHandlerTest.cs index a7790bb145f6..ec32ede42b6c 100644 --- a/src/Middleware/Diagnostics/test/UnitTests/ExceptionHandlerTest.cs +++ b/src/Middleware/Diagnostics/test/UnitTests/ExceptionHandlerTest.cs @@ -82,7 +82,7 @@ public async Task DoesNotHandle_UnhandledExceptions_WhenResponseAlreadyStarted() Exception exception = null; try { - await next(); + await next(httpContext); } catch (InvalidOperationException ex) { @@ -143,7 +143,7 @@ public async Task ClearsResponseBuffer_BeforeRequestIsReexecuted() try { - await next(); + await next(httpContext); } finally { @@ -328,7 +328,7 @@ public async Task DoesNotClearCacheHeaders_WhenResponseHasAlreadyStarted() Exception exception = null; try { - await next(); + await next(httpContext); } catch (InvalidOperationException ex) { @@ -483,7 +483,7 @@ public async Task ExceptionHandlerNotFound_ThrowsIOEWithOriginalError() Exception exception = null; try { - await next(); + await next(httpContext); } catch (InvalidOperationException ex) { diff --git a/src/Middleware/Diagnostics/test/UnitTests/StatusCodeMiddlewareTest.cs b/src/Middleware/Diagnostics/test/UnitTests/StatusCodeMiddlewareTest.cs index edd2478f4898..7a8cc2d0baaa 100644 --- a/src/Middleware/Diagnostics/test/UnitTests/StatusCodeMiddlewareTest.cs +++ b/src/Middleware/Diagnostics/test/UnitTests/StatusCodeMiddlewareTest.cs @@ -86,7 +86,7 @@ public async Task Reexecute_CanRetrieveInformationAboutOriginalRequest() app.Use(async (context, next) => { var beforeNext = context.Request.QueryString; - await next(); + await next(context); var afterNext = context.Request.QueryString; Assert.Equal(beforeNext, afterNext); @@ -150,7 +150,7 @@ public async Task Reexecute_ClearsEndpointAndRouteData() { Assert.Empty(context.Request.RouteValues); Assert.Null(context.GetEndpoint()); - return next(); + return next(context); }); app.Map(destination, (innerAppBuilder) => diff --git a/src/Middleware/Diagnostics/test/testassets/DeveloperExceptionPageSample/Startup.cs b/src/Middleware/Diagnostics/test/testassets/DeveloperExceptionPageSample/Startup.cs index 7ac337c8142e..c1756c6f5838 100644 --- a/src/Middleware/Diagnostics/test/testassets/DeveloperExceptionPageSample/Startup.cs +++ b/src/Middleware/Diagnostics/test/testassets/DeveloperExceptionPageSample/Startup.cs @@ -32,7 +32,7 @@ public void Configure(IApplicationBuilder app) "Endpoint display name"); context.SetEndpoint(endpoint); - return next(); + return next(context); }); app.UseDeveloperExceptionPage(); app.Run(context => diff --git a/src/Middleware/Diagnostics/test/testassets/StatusCodePagesSample/Startup.cs b/src/Middleware/Diagnostics/test/testassets/StatusCodePagesSample/Startup.cs index 76c82e8002b3..e145378879a7 100644 --- a/src/Middleware/Diagnostics/test/testassets/StatusCodePagesSample/Startup.cs +++ b/src/Middleware/Diagnostics/test/testassets/StatusCodePagesSample/Startup.cs @@ -55,7 +55,7 @@ public void Configure(IApplicationBuilder app) } else { - await next(); + await next(context); } }); diff --git a/src/Middleware/HostFiltering/test/HostFilteringMiddlewareTests.cs b/src/Middleware/HostFiltering/test/HostFilteringMiddlewareTests.cs index 9908f9248cc9..4076b5bd6bf9 100644 --- a/src/Middleware/HostFiltering/test/HostFilteringMiddlewareTests.cs +++ b/src/Middleware/HostFiltering/test/HostFilteringMiddlewareTests.cs @@ -61,7 +61,7 @@ public async Task AllowsMissingHost(bool allowed, int status) app.Use((ctx, next) => { ctx.Request.Headers.Remove(HeaderNames.Host); - return next(); + return next(ctx); }); app.UseHostFiltering(); app.Run(c => @@ -102,7 +102,7 @@ public async Task AllowsEmptyHost(bool allowed, int status) app.Use((ctx, next) => { ctx.Request.Headers[HeaderNames.Host] = ""; - return next(); + return next(ctx); }); app.UseHostFiltering(); app.Run(c => @@ -159,7 +159,7 @@ public async Task AllowsSpecifiedHost(string hosturl, string allowedHost) // TestHost's ClientHandler doesn't let you set the host header, only the host in the URI // and that would over-normalize some of our test conditions like casing. ctx.Request.Headers[HeaderNames.Host] = hosturl; - return next(); + return next(ctx); }); app.UseHostFiltering(); app.Run(c => Task.CompletedTask); @@ -211,7 +211,7 @@ public async Task RejectsMismatchedHosts(string hosturl, string allowedHost) // TestHost's ClientHandler doesn't let you set the host header, only the host in the URI // and that would reject some of our test conditions. ctx.Request.Headers[HeaderNames.Host] = hosturl; - return next(); + return next(ctx); }); app.UseHostFiltering(); app.Run(c => throw new NotImplementedException("App")); @@ -250,7 +250,7 @@ public async Task SupportsDynamicOptionsReload() app.Use((ctx, next) => { ctx.Request.Headers[HeaderNames.Host] = currentHost; - return next(); + return next(ctx); }); app.UseHostFiltering(); app.Run(c => Task.CompletedTask); diff --git a/src/Middleware/HttpOverrides/test/CertificateForwardingTest.cs b/src/Middleware/HttpOverrides/test/CertificateForwardingTest.cs index 6579a17b15ca..0491cca3d36b 100644 --- a/src/Middleware/HttpOverrides/test/CertificateForwardingTest.cs +++ b/src/Middleware/HttpOverrides/test/CertificateForwardingTest.cs @@ -57,13 +57,13 @@ public async Task VerifyHeaderIsUsedIfNoCertificateAlreadySet() app.Use(async (context, next) => { Assert.Null(context.Connection.ClientCertificate); - await next(); + await next(context); }); app.UseCertificateForwarding(); app.Use(async (context, next) => { Assert.Equal(context.Connection.ClientCertificate, Certificates.SelfSignedValidWithNoEku); - await next(); + await next(context); }); }); }).Build(); @@ -96,13 +96,13 @@ public async Task VerifyHeaderOverridesCertificateEvenAlreadySet() { Assert.Null(context.Connection.ClientCertificate); context.Connection.ClientCertificate = Certificates.SelfSignedNotYetValid; - await next(); + await next(context); }); app.UseCertificateForwarding(); app.Use(async (context, next) => { Assert.Equal(context.Connection.ClientCertificate, Certificates.SelfSignedValidWithNoEku); - await next(); + await next(context); }); }); }).Build(); @@ -134,13 +134,13 @@ public async Task VerifySettingTheAzureHeaderOnTheForwarderOptionsWorks() app.Use(async (context, next) => { Assert.Null(context.Connection.ClientCertificate); - await next(); + await next(context); }); app.UseCertificateForwarding(); app.Use(async (context, next) => { Assert.Equal(context.Connection.ClientCertificate, Certificates.SelfSignedValidWithNoEku); - await next(); + await next(context); }); }); }).Build(); @@ -172,13 +172,13 @@ public async Task VerifyACustomHeaderFailsIfTheHeaderIsNotPresent() app.Use(async (context, next) => { Assert.Null(context.Connection.ClientCertificate); - await next(); + await next(context); }); app.UseCertificateForwarding(); app.Use(async (context, next) => { Assert.Null(context.Connection.ClientCertificate); - await next(); + await next(context); }); }); }).Build(); @@ -210,13 +210,13 @@ public async Task VerifyArrHeaderEncodedCertFailsOnBadEncoding() app.Use(async (context, next) => { Assert.Null(context.Connection.ClientCertificate); - await next(); + await next(context); }); app.UseCertificateForwarding(); app.Use(async (context, next) => { Assert.Null(context.Connection.ClientCertificate); - await next(); + await next(context); }); }); }).Build(); diff --git a/src/Middleware/Localization/sample/Startup.cs b/src/Middleware/Localization/sample/Startup.cs index 3b8eef29f7d1..e9a303a1cb16 100644 --- a/src/Middleware/Localization/sample/Startup.cs +++ b/src/Middleware/Localization/sample/Startup.cs @@ -38,7 +38,7 @@ public void Configure(IApplicationBuilder app, IStringLocalizer SR) //})); ); - app.Use(async (context, next) => + app.Run(async (context) => { if (context.Request.Path.Value.EndsWith("favicon.ico", StringComparison.Ordinal)) { diff --git a/src/Middleware/MiddlewareAnalysis/samples/MiddlewareAnalysisSample/Startup.cs b/src/Middleware/MiddlewareAnalysis/samples/MiddlewareAnalysisSample/Startup.cs index de7ff66d1c41..76c760b2640a 100644 --- a/src/Middleware/MiddlewareAnalysis/samples/MiddlewareAnalysisSample/Startup.cs +++ b/src/Middleware/MiddlewareAnalysis/samples/MiddlewareAnalysisSample/Startup.cs @@ -33,7 +33,7 @@ public void Configure(IApplicationBuilder app, ILoggerFactory factory, Diagnosti app.Use((context, next) => { // No-op - return next(); + return next(context); }); app.Map("/map", subApp => @@ -74,7 +74,7 @@ public void Configure(IApplicationBuilder app, ILoggerFactory factory, Diagnosti } else { - await next(); + await next(context); } }); diff --git a/src/Middleware/ResponseCompression/test/ResponseCompressionMiddlewareTest.cs b/src/Middleware/ResponseCompression/test/ResponseCompressionMiddlewareTest.cs index e49da0be6ef6..7da04beb182b 100644 --- a/src/Middleware/ResponseCompression/test/ResponseCompressionMiddlewareTest.cs +++ b/src/Middleware/ResponseCompression/test/ResponseCompressionMiddlewareTest.cs @@ -980,7 +980,7 @@ public async Task SendFileAsync_DifferentContentType_NotBypassed() { fakeSendFile = new FakeSendFileFeature(context.Features.Get()); context.Features.Set(fakeSendFile); - return next(); + return next(context); }); app.UseResponseCompression(); app.Run(context => @@ -1030,7 +1030,7 @@ public async Task SendFileAsync_FirstWrite_CompressesAndFlushes() { fakeSendFile = new FakeSendFileFeature(context.Features.Get()); context.Features.Set(fakeSendFile); - return next(); + return next(context); }); app.UseResponseCompression(); app.Run(context => @@ -1080,7 +1080,7 @@ public async Task SendFileAsync_AfterFirstWrite_CompressesAndFlushes() { fakeSendFile = new FakeSendFileFeature(context.Features.Get()); context.Features.Set(fakeSendFile); - return next(); + return next(context); }); app.UseResponseCompression(); app.Run(async context => @@ -1130,7 +1130,7 @@ public async Task Dispose_SyncWriteOrFlushNotCalled(string encoding) app.Use((context, next) => { context.Response.Body = new NoSyncWrapperStream(context.Response.Body); - return next(); + return next(context); }); app.UseResponseCompression(); app.Run(async context => diff --git a/src/Middleware/Session/test/SessionTests.cs b/src/Middleware/Session/test/SessionTests.cs index 2619c5e691ed..6e675cde63a1 100644 --- a/src/Middleware/Session/test/SessionTests.cs +++ b/src/Middleware/Session/test/SessionTests.cs @@ -524,7 +524,7 @@ public async Task SessionFeature_IsUnregistered_WhenResponseGoingOut() { app.Use(async (httpContext, next) => { - await next(); + await next(httpContext); Assert.Null(httpContext.Features.Get()); }); @@ -569,7 +569,7 @@ public async Task SessionFeature_IsUnregistered_WhenResponseGoingOut_AndAnUnhand var exceptionThrown = false; try { - await next(); + await next(httpContext); } catch { diff --git a/src/Middleware/Spa/SpaServices.Extensions/src/Proxying/SpaProxyingExtensions.cs b/src/Middleware/Spa/SpaServices.Extensions/src/Proxying/SpaProxyingExtensions.cs index 7b0b48b6d3d7..e37c080cf7cc 100644 --- a/src/Middleware/Spa/SpaServices.Extensions/src/Proxying/SpaProxyingExtensions.cs +++ b/src/Middleware/Spa/SpaServices.Extensions/src/Proxying/SpaProxyingExtensions.cs @@ -75,7 +75,7 @@ public static void UseProxyToSpaDevelopmentServer( SpaProxy.CreateHttpClientForProxy(Timeout.InfiniteTimeSpan); // Proxy all requests to the SPA development server - applicationBuilder.Use(async (context, next) => + applicationBuilder.Run(async (context) => { var didProxyRequest = await SpaProxy.PerformProxyRequest( context, neverTimeOutHttpClient, baseUriTaskFactory(), applicationStoppingToken, diff --git a/src/Middleware/Spa/SpaServices.Extensions/src/SpaDefaultPageMiddleware.cs b/src/Middleware/Spa/SpaServices.Extensions/src/SpaDefaultPageMiddleware.cs index ab81d79129a0..3a65a46ed914 100644 --- a/src/Middleware/Spa/SpaServices.Extensions/src/SpaDefaultPageMiddleware.cs +++ b/src/Middleware/Spa/SpaServices.Extensions/src/SpaDefaultPageMiddleware.cs @@ -28,11 +28,11 @@ public static void Attach(ISpaBuilder spaBuilder) // If we have an Endpoint, then this is a deferred match - just noop. if (context.GetEndpoint() != null) { - return next(); + return next(context); } context.Request.Path = options.DefaultPage; - return next(); + return next(context); }); // Serve it as a static file @@ -49,7 +49,7 @@ public static void Attach(ISpaBuilder spaBuilder) // If we have an Endpoint, then this is a deferred match - just noop. if (context.GetEndpoint() != null) { - return next(); + return next(context); } var message = "The SPA default page middleware could not return the default page " + diff --git a/src/Middleware/StaticFiles/test/FunctionalTests/StaticFileMiddlewareTests.cs b/src/Middleware/StaticFiles/test/FunctionalTests/StaticFileMiddlewareTests.cs index 14183c0647f4..dc4cc9d86468 100644 --- a/src/Middleware/StaticFiles/test/FunctionalTests/StaticFileMiddlewareTests.cs +++ b/src/Middleware/StaticFiles/test/FunctionalTests/StaticFileMiddlewareTests.cs @@ -261,7 +261,7 @@ private async Task ClientDisconnect_NoWriteExceptionThrown(ServerType serverType requestReceived.SetResult(0); await requestCancelled.Task.TimeoutAfter(interval); Assert.True(context.RequestAborted.WaitHandle.WaitOne(interval), "not aborted"); - await next(); + await next(context); } catch (Exception ex) { diff --git a/src/Middleware/StaticFiles/test/UnitTests/StaticFileMiddlewareTests.cs b/src/Middleware/StaticFiles/test/UnitTests/StaticFileMiddlewareTests.cs index 518927b50976..ce127de3da55 100644 --- a/src/Middleware/StaticFiles/test/UnitTests/StaticFileMiddlewareTests.cs +++ b/src/Middleware/StaticFiles/test/UnitTests/StaticFileMiddlewareTests.cs @@ -97,7 +97,7 @@ public async Task ReturnsNotFoundIfSendFileThrows() app.Use(async (ctx, next) => { ctx.Features.Set(mockSendFile.Object); - await next(); + await next(ctx); }); app.UseStaticFiles(new StaticFileOptions { ServeUnknownFileTypes = true }); }) diff --git a/src/Middleware/WebSockets/samples/EchoApp/Startup.cs b/src/Middleware/WebSockets/samples/EchoApp/Startup.cs index 5f8761705400..f1d828955aab 100644 --- a/src/Middleware/WebSockets/samples/EchoApp/Startup.cs +++ b/src/Middleware/WebSockets/samples/EchoApp/Startup.cs @@ -42,7 +42,7 @@ public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerF } else { - await next(); + await next(context); } }); diff --git a/src/Middleware/WebSockets/test/ConformanceTests/AutobahnTestApp/Startup.cs b/src/Middleware/WebSockets/test/ConformanceTests/AutobahnTestApp/Startup.cs index 6c94e5e22b2c..f8b75268c28b 100644 --- a/src/Middleware/WebSockets/test/ConformanceTests/AutobahnTestApp/Startup.cs +++ b/src/Middleware/WebSockets/test/ConformanceTests/AutobahnTestApp/Startup.cs @@ -17,7 +17,7 @@ public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory) app.UseWebSockets(); var logger = loggerFactory.CreateLogger(); - app.Use(async (context, next) => + app.Run(async (context) => { if (context.WebSockets.IsWebSocketRequest) { diff --git a/src/Middleware/WebSockets/test/UnitTests/KestrelWebSocketHelpers.cs b/src/Middleware/WebSockets/test/UnitTests/KestrelWebSocketHelpers.cs index 238e874683c1..73182e7cf00d 100644 --- a/src/Middleware/WebSockets/test/UnitTests/KestrelWebSocketHelpers.cs +++ b/src/Middleware/WebSockets/test/UnitTests/KestrelWebSocketHelpers.cs @@ -27,7 +27,7 @@ public static IDisposable CreateServer(ILoggerFactory loggerFactory, out int por { // Kestrel does not return proper error responses: // https://github.com/aspnet/KestrelHttpServer/issues/43 - await next(); + await next(ct); } catch (Exception ex) { diff --git a/src/Mvc/Mvc.Core/test/Filters/MiddlewareFilterAttributeTest.cs b/src/Mvc/Mvc.Core/test/Filters/MiddlewareFilterAttributeTest.cs index e6912b1ff904..56964294a080 100644 --- a/src/Mvc/Mvc.Core/test/Filters/MiddlewareFilterAttributeTest.cs +++ b/src/Mvc/Mvc.Core/test/Filters/MiddlewareFilterAttributeTest.cs @@ -26,7 +26,7 @@ public void CreatesMiddlewareFilter_WithConfiguredPipeline() configureCallCount++; ab.Use((httpContext, next) => { - return next(); + return next(httpContext); }); }; diff --git a/src/Mvc/Mvc.Core/test/Filters/MiddlewareFilterBuilderTest.cs b/src/Mvc/Mvc.Core/test/Filters/MiddlewareFilterBuilderTest.cs index 2d6a4fa11cdb..fc2239fcffed 100644 --- a/src/Mvc/Mvc.Core/test/Filters/MiddlewareFilterBuilderTest.cs +++ b/src/Mvc/Mvc.Core/test/Filters/MiddlewareFilterBuilderTest.cs @@ -91,9 +91,9 @@ public async Task EndMiddleware_ThrowsException_WhenMiddleFeature_NotAvailable() var httpContext = new DefaultHttpContext(); Pipeline1.ConfigurePipeline = ab => { - ab.Use((_, next) => + ab.Use((ctx, next) => { - return next(); + return next(ctx); }); }; @@ -119,9 +119,9 @@ public async Task EndMiddleware_DoesNotThrow_IfExceptionHandled() Pipeline1.ConfigurePipeline = ab => { - ab.Use((_, next) => + ab.Use((ctx, next) => { - return next(); + return next(ctx); }); }; @@ -171,9 +171,9 @@ public async Task EndMiddleware_PropagatesBackException_ToEarlierMiddleware() Pipeline1.ConfigurePipeline = ab => { - ab.Use((_, next) => + ab.Use((ctx, next) => { - return next(); + return next(ctx); }); }; @@ -239,9 +239,9 @@ public async Task EndMiddleware_PropagatesFullExceptionInfo_ToEarlierMiddleware( Pipeline1.ConfigurePipeline = ab => { - ab.Use((_, next) => + ab.Use((ctx, next) => { - return next(); + return next(ctx); }); }; diff --git a/src/Mvc/Mvc.Core/test/Filters/MiddlewareFilterTest.cs b/src/Mvc/Mvc.Core/test/Filters/MiddlewareFilterTest.cs index 5b02a3be9769..0ddfbe40e5ae 100644 --- a/src/Mvc/Mvc.Core/test/Filters/MiddlewareFilterTest.cs +++ b/src/Mvc/Mvc.Core/test/Filters/MiddlewareFilterTest.cs @@ -56,7 +56,7 @@ public async Task OnMiddlewareShortCircuit_DoesNotExecute_RestOfFilterPipeline() var expectedHeader = "h1"; Pipeline1.ConfigurePipeline = (appBuilder) => { - appBuilder.Use((httpContext, next) => + appBuilder.Run((httpContext) => { httpContext.Response.Headers.Add(expectedHeader, ""); return Task.FromResult(true); // short circuit the request @@ -97,12 +97,12 @@ public async Task Multiple_MiddlewareFilters_ConcatsTheMiddlewarePipelines() appBuilder.Use((httpContext, next) => { httpContext.Response.Headers["h1"] = "pipeline1"; - return next(); + return next(httpContext); }); }; Pipeline2.ConfigurePipeline = (appBuilder) => { - appBuilder.Use((httpContext, next) => + appBuilder.Run((httpContext) => { httpContext.Response.Headers["h1"] = httpContext.Response.Headers["h1"] + "-pipeline2"; return Task.FromResult(true); // short circuits the request @@ -142,7 +142,7 @@ public async Task UnhandledException_InMiddleware_PropagatesBackToInvoker() var expectedMessage = "Error!!!"; Pipeline1.ConfigurePipeline = (appBuilder) => { - appBuilder.Use((httpContext, next) => + appBuilder.Run((httpContext) => { throw new InvalidOperationException(expectedMessage); }); @@ -178,7 +178,7 @@ public async Task ExceptionThrownInMiddleware_CanBeHandled_ByEarlierMiddleware() { try { - await next(); + await next(httpContext); } catch { @@ -189,7 +189,7 @@ public async Task ExceptionThrownInMiddleware_CanBeHandled_ByEarlierMiddleware() }; Pipeline2.ConfigurePipeline = (appBuilder) => { - appBuilder.Use((httpContext, next) => + appBuilder.Run((httpContext) => { throw new InvalidOperationException(expectedMessage); }); diff --git a/src/Mvc/test/WebSites/BasicWebSite/StartupRequestLimitSize.cs b/src/Mvc/test/WebSites/BasicWebSite/StartupRequestLimitSize.cs index f07cd83b6a26..f8ce10236295 100644 --- a/src/Mvc/test/WebSites/BasicWebSite/StartupRequestLimitSize.cs +++ b/src/Mvc/test/WebSites/BasicWebSite/StartupRequestLimitSize.cs @@ -35,7 +35,7 @@ public void Configure(IApplicationBuilder app) httpContext.Request.Body, testHttpMaxRequestBodySizeFeature); - return next(); + return next(httpContext); }); app.UseRouting(); diff --git a/src/Mvc/test/WebSites/BasicWebSite/StartupWhereReadingRequestBodyThrows.cs b/src/Mvc/test/WebSites/BasicWebSite/StartupWhereReadingRequestBodyThrows.cs index 7e0b0c6637e7..2e3e2f1b9da5 100644 --- a/src/Mvc/test/WebSites/BasicWebSite/StartupWhereReadingRequestBodyThrows.cs +++ b/src/Mvc/test/WebSites/BasicWebSite/StartupWhereReadingRequestBodyThrows.cs @@ -31,7 +31,7 @@ public void Configure(IApplicationBuilder app) app.Use((context, next) => { context.Request.Body = new ThrowingStream(); - return next(); + return next(context); }); app.UseRouting(); diff --git a/src/Security/Authentication/JwtBearer/samples/JwtBearerSample/Startup.cs b/src/Security/Authentication/JwtBearer/samples/JwtBearerSample/Startup.cs index 4f8831b29eb0..d88ad22b8ce1 100644 --- a/src/Security/Authentication/JwtBearer/samples/JwtBearerSample/Startup.cs +++ b/src/Security/Authentication/JwtBearer/samples/JwtBearerSample/Startup.cs @@ -59,7 +59,7 @@ public void Configure(IApplicationBuilder app) var authResult = await context.AuthenticateAsync(JwtBearerDefaults.AuthenticationScheme); if (authResult.Succeeded && authResult.Principal.Identity.IsAuthenticated) { - await next(); + await next(context); } else if (authResult.Failure != null) { diff --git a/src/Security/Authentication/test/CertificateTests.cs b/src/Security/Authentication/test/CertificateTests.cs index 6b805aaa623d..dac2cc2f3388 100644 --- a/src/Security/Authentication/test/CertificateTests.cs +++ b/src/Security/Authentication/test/CertificateTests.cs @@ -701,7 +701,7 @@ private static async Task CreateHost( { context.Connection.ClientCertificate = clientCertificate; } - return next(); + return next(context); }); @@ -712,7 +712,7 @@ private static async Task CreateHost( app.UseAuthentication(); - app.Use(async (context, next) => + app.Run(async (context) => { var request = context.Request; var response = context.Response; diff --git a/src/Security/Authentication/test/CookieTests.cs b/src/Security/Authentication/test/CookieTests.cs index 41d70c1be658..f01ad7f5496d 100644 --- a/src/Security/Authentication/test/CookieTests.cs +++ b/src/Security/Authentication/test/CookieTests.cs @@ -1403,7 +1403,7 @@ public async Task CanSpecifyAndShareDataProtector() .Configure(app => { app.UseAuthentication(); - app.Use((context, next) => + app.Run((context) => context.SignInAsync("Cookies", new ClaimsPrincipal(new ClaimsIdentity(new GenericIdentity("Alice", "Cookies"))), new AuthenticationProperties())); @@ -1426,7 +1426,7 @@ public async Task CanSpecifyAndShareDataProtector() .Configure(app => { app.UseAuthentication(); - app.Use(async (context, next) => + app.Run(async (context) => { var result = await context.AuthenticateAsync("Cookies"); await DescribeAsync(context.Response, result); @@ -1635,7 +1635,7 @@ private static async Task CreateHostWithServices(Action CreateHost(Action configure } else { - await next(); + await next(context); } }); }) diff --git a/src/Security/Authentication/test/FacebookTests.cs b/src/Security/Authentication/test/FacebookTests.cs index 5819186c3f3f..ca8561c2690d 100644 --- a/src/Security/Authentication/test/FacebookTests.cs +++ b/src/Security/Authentication/test/FacebookTests.cs @@ -383,7 +383,7 @@ private static async Task CreateHost(Action configur { if (handler == null || !await handler(context)) { - await next(); + await next(context); } }); }) diff --git a/src/Security/Authentication/test/GoogleTests.cs b/src/Security/Authentication/test/GoogleTests.cs index 9b8b0e7a784c..cacff91a37d4 100644 --- a/src/Security/Authentication/test/GoogleTests.cs +++ b/src/Security/Authentication/test/GoogleTests.cs @@ -1148,7 +1148,7 @@ private static async Task CreateHost(Action configureOptio } else { - await next(); + await next(context); } }); }) diff --git a/src/Security/Authentication/test/JwtBearerTests.cs b/src/Security/Authentication/test/JwtBearerTests.cs index be87343edf7e..b8361cb61dfe 100755 --- a/src/Security/Authentication/test/JwtBearerTests.cs +++ b/src/Security/Authentication/test/JwtBearerTests.cs @@ -1018,7 +1018,7 @@ private static async Task CreateHost(Action options = n } else { - await next(); + await next(context); } }); }) diff --git a/src/Security/Authentication/test/MicrosoftAccountTests.cs b/src/Security/Authentication/test/MicrosoftAccountTests.cs index 481b714ab73c..5fd52e82ee1e 100644 --- a/src/Security/Authentication/test/MicrosoftAccountTests.cs +++ b/src/Security/Authentication/test/MicrosoftAccountTests.cs @@ -410,7 +410,7 @@ private static async Task CreateHost(Action conf } else { - await next(); + await next(context); } }); }) diff --git a/src/Security/Authentication/test/OAuthTests.cs b/src/Security/Authentication/test/OAuthTests.cs index 83e835d19be5..7d54fe8f260f 100644 --- a/src/Security/Authentication/test/OAuthTests.cs +++ b/src/Security/Authentication/test/OAuthTests.cs @@ -406,9 +406,9 @@ private static async Task CreateHost(Action configure app.UseAuthentication(); app.Use(async (context, next) => { - if (handler == null || ! await handler(context)) + if (handler == null || !await handler(context)) { - await next(); + await next(context); } }); }) diff --git a/src/Security/Authentication/test/OpenIdConnect/TestServerBuilder.cs b/src/Security/Authentication/test/OpenIdConnect/TestServerBuilder.cs index 41fd484b733f..7d15cac7b269 100644 --- a/src/Security/Authentication/test/OpenIdConnect/TestServerBuilder.cs +++ b/src/Security/Authentication/test/OpenIdConnect/TestServerBuilder.cs @@ -106,7 +106,7 @@ await context.SignOutAsync( } else { - await next(); + await next(context); } }); }) diff --git a/src/Security/Authentication/test/PolicyTests.cs b/src/Security/Authentication/test/PolicyTests.cs index 5049635b1aa7..dbd56884323e 100644 --- a/src/Security/Authentication/test/PolicyTests.cs +++ b/src/Security/Authentication/test/PolicyTests.cs @@ -477,7 +477,7 @@ private static async Task CreateServer(Action co } else { - await next(); + await next(context); } }); }) diff --git a/src/Security/Authentication/test/RemoteAuthenticationTests.cs b/src/Security/Authentication/test/RemoteAuthenticationTests.cs index 7222a759028a..af6b19fc5f10 100644 --- a/src/Security/Authentication/test/RemoteAuthenticationTests.cs +++ b/src/Security/Authentication/test/RemoteAuthenticationTests.cs @@ -43,7 +43,7 @@ protected virtual async Task CreateHostWithServices(Action CreateHost(Action options, Func } else if (handler == null || !await handler(context)) { - await next(); + await next(context); } }); }) diff --git a/src/Security/samples/StaticFilesAuth/Startup.cs b/src/Security/samples/StaticFilesAuth/Startup.cs index 04025b5387ca..dc176db65825 100644 --- a/src/Security/samples/StaticFilesAuth/Startup.cs +++ b/src/Security/samples/StaticFilesAuth/Startup.cs @@ -95,13 +95,13 @@ public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IAuthori app.Map("/MapAuthenticatedFiles", branch => { - branch.Use((context, next) => { SetFileEndpoint(context, files, null); return next(); }); + branch.Use((context, next) => { SetFileEndpoint(context, files, null); return next(context); }); branch.UseAuthorization(); SetupFileServer(branch, files); }); app.Map("/MapImperativeFiles", branch => { - branch.Use((context, next) => { SetFileEndpoint(context, files, "files"); return next(); }); + branch.Use((context, next) => { SetFileEndpoint(context, files, "files"); return next(context); }); branch.UseAuthorization(); SetupFileServer(branch, files); }); diff --git a/src/Servers/HttpSys/samples/HotAddSample/Startup.cs b/src/Servers/HttpSys/samples/HotAddSample/Startup.cs index a0efd408f1a3..899dabddf22a 100644 --- a/src/Servers/HttpSys/samples/HotAddSample/Startup.cs +++ b/src/Servers/HttpSys/samples/HotAddSample/Startup.cs @@ -52,7 +52,7 @@ public void Configure(IApplicationBuilder app) await context.Response.WriteAsync(""); return; } - await next(); + await next(context); }); app.Use(async (context, next) => @@ -76,7 +76,7 @@ public void Configure(IApplicationBuilder app) await context.Response.WriteAsync(""); return; } - await next(); + await next(context); }); app.Run(async context => diff --git a/src/Servers/Kestrel/samples/SampleApp/Startup.cs b/src/Servers/Kestrel/samples/SampleApp/Startup.cs index 553c5747a3a1..6617e019ac3c 100644 --- a/src/Servers/Kestrel/samples/SampleApp/Startup.cs +++ b/src/Servers/Kestrel/samples/SampleApp/Startup.cs @@ -35,7 +35,7 @@ public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory) try { - await next.Invoke(); + await next.Invoke(context); } catch (Microsoft.AspNetCore.Http.BadHttpRequestException ex) when (ex.StatusCode == StatusCodes.Status413RequestEntityTooLarge) { } }); diff --git a/src/Servers/testassets/ServerComparison.TestSites/StartupNtlmAuthentication.cs b/src/Servers/testassets/ServerComparison.TestSites/StartupNtlmAuthentication.cs index 9fc54386b1f6..7cb07e5c8997 100644 --- a/src/Servers/testassets/ServerComparison.TestSites/StartupNtlmAuthentication.cs +++ b/src/Servers/testassets/ServerComparison.TestSites/StartupNtlmAuthentication.cs @@ -30,7 +30,7 @@ public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory) { try { - await next(); + await next(context); } catch (Exception ex) { @@ -45,7 +45,7 @@ public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory) }); app.UseAuthentication(); - app.Use((context, next) => + app.Run((context) => { if (context.Request.Path.Equals("/Anonymous")) { diff --git a/src/SignalR/clients/ts/FunctionalTests/Startup.cs b/src/SignalR/clients/ts/FunctionalTests/Startup.cs index 2c2dfd420210..ca5ce0fdab40 100644 --- a/src/SignalR/clients/ts/FunctionalTests/Startup.cs +++ b/src/SignalR/clients/ts/FunctionalTests/Startup.cs @@ -145,7 +145,7 @@ public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILogger< return Task.CompletedTask; } - return next.Invoke(); + return next.Invoke(context); }); app.Use((context, next) => @@ -159,7 +159,7 @@ public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILogger< return Task.CompletedTask; } - return next.Invoke(); + return next.Invoke(context); }); app.Use((context, next) => @@ -170,7 +170,7 @@ public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILogger< return context.Response.WriteAsync($"{{ \"url\": \"{newUrl}\" }}"); } - return next(); + return next(context); }); app.Use(async (context, next) => @@ -194,7 +194,7 @@ public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILogger< context.Response.Cookies.Append("expiredCookie", "doesntmatter", expiredCookieOptions); } - await next.Invoke(); + await next.Invoke(context); }); app.Use((context, next) => @@ -205,7 +205,7 @@ public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILogger< return context.Response.WriteAsync("Some response from server"); } - return next(); + return next(context); }); app.UseRouting();