Skip to content

Fix UsePathBase with WAB #42876

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Aug 12, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions src/DefaultBuilder/src/WebApplicationBuilder.cs
Original file line number Diff line number Diff line change
@@ -20,6 +20,7 @@ public sealed class WebApplicationBuilder
private const string EndpointRouteBuilderKey = "__EndpointRouteBuilder";
private const string AuthenticationMiddlewareSetKey = "__AuthenticationMiddlewareSet";
private const string AuthorizationMiddlewareSetKey = "__AuthorizationMiddlewareSet";
private const string UseRoutingKey = "__UseRouting";

private readonly HostApplicationBuilder _hostApplicationBuilder;
private readonly ServiceDescriptor _genericWebHostServiceDescriptor;
@@ -162,6 +163,8 @@ private void ConfigureApplication(WebHostBuilderContext context, IApplicationBui
if (!_builtApplication.Properties.TryGetValue(EndpointRouteBuilderKey, out var localRouteBuilder))
{
app.UseRouting();
// Middleware the needs to re-route will use this property to call UseRouting()
_builtApplication.Properties[UseRoutingKey] = app.Properties[UseRoutingKey];
}
else
{
Original file line number Diff line number Diff line change
@@ -3,6 +3,7 @@

using Microsoft.AspNetCore.Builder.Extensions;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;

namespace Microsoft.AspNetCore.Builder;

@@ -31,6 +32,16 @@ public static IApplicationBuilder UsePathBase(this IApplicationBuilder app, Path
return app;
}

// Only use this path if there's a global router (in the 'WebApplication' case).
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I know this isn't new, but is there really a scenario for calling UsePathBase() after route matching with or without WebApplication? I'm not saying we change this now, just curious.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pretty sure we had the same question for some of the other middleware when we initially created this "global routing" concept. And the answer was, why not make it work if it's easy.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

And the answer was, why not make it work if it's easy.

Then why didn't we make it work in the non-'WebApplication' case? This isn't feedback on the PR. I think we should leave it how you have it since it's a bit late to change that kind of behavior.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

non WAB doesn't have the global routing concept, and we don't have a way to effectively inject middleware before UseRouting.

if (app.Properties.TryGetValue(RerouteHelper.GlobalRouteBuilderKey, out var routeBuilder) && routeBuilder is not null)
{
return app.Use(next =>
{
var newNext = RerouteHelper.Reroute(app, routeBuilder, next);
return new UsePathBaseMiddleware(newNext, pathBase).Invoke;
});
}

return app.UseMiddleware<UsePathBaseMiddleware>(pathBase);
}
}
Original file line number Diff line number Diff line change
@@ -28,6 +28,7 @@ Microsoft.AspNetCore.Http.HttpResponse</Description>
<Compile Include="$(SharedSourceRoot)ValueTaskExtensions\**\*.cs" />
<Compile Include="$(SharedSourceRoot)ProblemDetails\HttpValidationProblemDetailsJsonConverter.cs" LinkBase="ProblemDetails\Converters" />
<Compile Include="$(SharedSourceRoot)ProblemDetails\ProblemDetailsJsonConverter.cs" LinkBase="ProblemDetails\Converters" />
<Compile Include="$(SharedSourceRoot)Reroute.cs" />
</ItemGroup>

<ItemGroup>
Original file line number Diff line number Diff line change
@@ -10,8 +10,10 @@
</ItemGroup>

<ItemGroup>
<Reference Include="Microsoft.AspNetCore" />
<Reference Include="Microsoft.AspNetCore.Http" />
<Reference Include="Microsoft.AspNetCore.Routing" />
<Reference Include="Microsoft.AspNetCore.TestHost" />
<Reference Include="Mono.TextTemplating" />
</ItemGroup>

68 changes: 68 additions & 0 deletions src/Http/Http.Abstractions/test/UsePathBaseExtensionsTests.cs
Original file line number Diff line number Diff line change
@@ -3,6 +3,7 @@

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.TestHost;

namespace Microsoft.AspNetCore.Builder.Extensions;

@@ -138,6 +139,73 @@ public Task PathBaseCanHavePercentCharacters(string registeredPathBase, string p
return TestPathBase(registeredPathBase, pathBase, requestPath, expectedPathBase, expectedPath);
}

[Fact]
public async Task PathBaseWorksAfterUseRoutingIfGlobalRouteBuilderUsed()
{
var builder = WebApplication.CreateBuilder();
builder.WebHost.UseTestServer();
await using var app = builder.Build();

app.UseRouting();

app.UsePathBase("/base");

app.UseEndpoints(endpoints =>
{
endpoints.Map("/path", context => context.Response.WriteAsync("Response"));
});

await app.StartAsync();

using var server = app.GetTestServer();

var response = await server.CreateClient().GetStringAsync("/base/path");

Assert.Equal("Response", response);
}

[Fact]
public async Task PathBaseWorksBeforeUseRoutingIfGlobalRouteBuilderUsed()
{
var builder = WebApplication.CreateBuilder();
builder.WebHost.UseTestServer();
await using var app = builder.Build();

app.UsePathBase("/base");

app.UseRouting();

app.MapGet("/path", context => context.Response.WriteAsync("Response"));

await app.StartAsync();

using var server = app.GetTestServer();

var response = await server.CreateClient().GetStringAsync("/base/path");

Assert.Equal("Response", response);
}

[Fact]
public async Task PathBaseWorksWithoutUseRoutingWithWebApplication()
{
var builder = WebApplication.CreateBuilder();
builder.WebHost.UseTestServer();
await using var app = builder.Build();

app.UsePathBase("/base");

app.MapGet("/path", context => context.Response.WriteAsync("Response"));

await app.StartAsync();

using var server = app.GetTestServer();

var response = await server.CreateClient().GetStringAsync("/base/path");

Assert.Equal("Response", response);
}

private static async Task TestPathBase(string registeredPathBase, string pathBase, string requestPath, string expectedPathBase, string expectedPath)
{
HttpContext requestContext = CreateRequest(pathBase, requestPath);
Original file line number Diff line number Diff line change
@@ -15,6 +15,7 @@ public static class EndpointRoutingApplicationBuilderExtensions
{
private const string EndpointRouteBuilder = "__EndpointRouteBuilder";
private const string GlobalEndpointRouteBuilderKey = "__GlobalEndpointRouteBuilder";
private const string UseRoutingKey = "__UseRouting";

/// <summary>
/// Adds a <see cref="EndpointRoutingMiddleware"/> middleware to the specified <see cref="IApplicationBuilder"/>.
@@ -54,6 +55,10 @@ public static IApplicationBuilder UseRouting(this IApplicationBuilder builder)
builder.Properties[EndpointRouteBuilder] = endpointRouteBuilder;
}

// Add UseRouting function to properties so that middleware that can't reference UseRouting directly can call UseRouting via this property
// This is part of the global endpoint route builder concept
builder.Properties.TryAdd(UseRoutingKey, (object)UseRouting);

return builder.UseMiddleware<EndpointRoutingMiddleware>(endpointRouteBuilder);
}

Original file line number Diff line number Diff line change
@@ -4,6 +4,7 @@
using System.Diagnostics;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
@@ -103,13 +104,12 @@ public static IApplicationBuilder UseExceptionHandler(this IApplicationBuilder a

private static IApplicationBuilder SetExceptionHandlerMiddleware(IApplicationBuilder app, IOptions<ExceptionHandlerOptions>? options)
{
const string globalRouteBuilderKey = "__GlobalEndpointRouteBuilder";
var problemDetailsService = app.ApplicationServices.GetService<IProblemDetailsService>();

app.Properties["analysis.NextMiddlewareName"] = "Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware";

// Only use this path if there's a global router (in the 'WebApplication' case).
if (app.Properties.TryGetValue(globalRouteBuilderKey, out var routeBuilder) && routeBuilder is not null)
if (app.Properties.TryGetValue(RerouteHelper.GlobalRouteBuilderKey, out var routeBuilder) && routeBuilder is not null)
{
return app.Use(next =>
{
@@ -123,16 +123,9 @@ private static IApplicationBuilder SetExceptionHandlerMiddleware(IApplicationBui

if (!string.IsNullOrEmpty(options.Value.ExceptionHandlingPath) && options.Value.ExceptionHandler is null)
{
// start a new middleware pipeline
var builder = app.New();
// use the old routing pipeline if it exists so we preserve all the routes and matching logic
// ((IApplicationBuilder)WebApplication).New() does not copy globalRouteBuilderKey automatically like it does for all other properties.
builder.Properties[globalRouteBuilderKey] = routeBuilder;
builder.UseRouting();
// apply the next middleware
builder.Run(next);
var newNext = RerouteHelper.Reroute(app, routeBuilder, next);
// store the pipeline for the error case
options.Value.ExceptionHandler = builder.Build();
options.Value.ExceptionHandler = newNext;
}

return new ExceptionHandlerMiddlewareImpl(next, loggerFactory, options, diagnosticListener, problemDetailsService).Invoke;
Original file line number Diff line number Diff line change
@@ -15,6 +15,7 @@
<Compile Include="$(SharedSourceRoot)RazorViews\*.cs" />
<Compile Include="$(SharedSourceRoot)StackTrace\**\*.cs" />
<Compile Include="$(SharedSourceRoot)TypeNameHelper\*.cs" />
<Compile Include="$(SharedSourceRoot)Reroute.cs" />
</ItemGroup>

<ItemGroup>
Original file line number Diff line number Diff line change
@@ -5,6 +5,7 @@
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.Options;

namespace Microsoft.AspNetCore.Builder;
@@ -172,23 +173,12 @@ public static IApplicationBuilder UseStatusCodePagesWithReExecute(
throw new ArgumentNullException(nameof(app));
}

const string globalRouteBuilderKey = "__GlobalEndpointRouteBuilder";
// Only use this path if there's a global router (in the 'WebApplication' case).
if (app.Properties.TryGetValue(globalRouteBuilderKey, out var routeBuilder) && routeBuilder is not null)
if (app.Properties.TryGetValue(RerouteHelper.GlobalRouteBuilderKey, out var routeBuilder) && routeBuilder is not null)
{
return app.Use(next =>
{
RequestDelegate? newNext = null;
// start a new middleware pipeline
var builder = app.New();
// use the old routing pipeline if it exists so we preserve all the routes and matching logic
// ((IApplicationBuilder)WebApplication).New() does not copy globalRouteBuilderKey automatically like it does for all other properties.
builder.Properties[globalRouteBuilderKey] = routeBuilder;
builder.UseRouting();
// apply the next middleware
builder.Run(next);
newNext = builder.Build();

var newNext = RerouteHelper.Reroute(app, routeBuilder, next);
return new StatusCodePagesMiddleware(next,
Options.Create(new StatusCodePagesOptions() { HandleAsync = CreateHandler(pathFormat, queryFormat, newNext) })).Invoke;
});
Original file line number Diff line number Diff line change
@@ -23,4 +23,8 @@
<Reference Include="Microsoft.AspNetCore.Routing" />
</ItemGroup>

<ItemGroup>
<Compile Include="$(SharedSourceRoot)Reroute.cs" />
</ItemGroup>

</Project>
15 changes: 4 additions & 11 deletions src/Middleware/Rewrite/src/RewriteBuilderExtensions.cs
Original file line number Diff line number Diff line change
@@ -3,6 +3,7 @@

using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Rewrite;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
@@ -53,9 +54,8 @@ public static IApplicationBuilder UseRewriter(this IApplicationBuilder app, Rewr

private static IApplicationBuilder AddRewriteMiddleware(IApplicationBuilder app, IOptions<RewriteOptions>? options)
{
const string globalRouteBuilderKey = "__GlobalEndpointRouteBuilder";
// Only use this path if there's a global router (in the 'WebApplication' case).
if (app.Properties.TryGetValue(globalRouteBuilderKey, out var routeBuilder) && routeBuilder is not null)
if (app.Properties.TryGetValue(RerouteHelper.GlobalRouteBuilderKey, out var routeBuilder) && routeBuilder is not null)
{
return app.Use(next =>
{
@@ -67,15 +67,8 @@ private static IApplicationBuilder AddRewriteMiddleware(IApplicationBuilder app,
var webHostEnv = app.ApplicationServices.GetRequiredService<IWebHostEnvironment>();
var loggerFactory = app.ApplicationServices.GetRequiredService<ILoggerFactory>();

// start a new middleware pipeline
var builder = app.New();
// use the old routing pipeline if it exists so we preserve all the routes and matching logic
// ((IApplicationBuilder)WebApplication).New() does not copy globalRouteBuilderKey automatically like it does for all other properties.
builder.Properties[globalRouteBuilderKey] = routeBuilder;
builder.UseRouting();
// apply the next middleware
builder.Run(next);
options.Value.BranchedNext = builder.Build();
var newNext = RerouteHelper.Reroute(app, routeBuilder, next);
options.Value.BranchedNext = newNext;

return new RewriteMiddleware(next, webHostEnv, loggerFactory, options).Invoke;
});
34 changes: 34 additions & 0 deletions src/Shared/Reroute.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;

namespace Microsoft.AspNetCore.Routing;

internal static class RerouteHelper
{
internal const string GlobalRouteBuilderKey = "__GlobalEndpointRouteBuilder";
internal const string UseRoutingKey = "__UseRouting";

internal static RequestDelegate Reroute(IApplicationBuilder app, object routeBuilder, RequestDelegate next)
{
if (app.Properties.TryGetValue(UseRoutingKey, out var useRouting) && useRouting is Func<IApplicationBuilder, IApplicationBuilder> useRoutingFunc)
{
var builder = app.New();
// use the old routing pipeline if it exists so we preserve all the routes and matching logic
// ((IApplicationBuilder)WebApplication).New() does not copy GlobalRouteBuilderKey automatically like it does for all other properties.
builder.Properties[GlobalRouteBuilderKey] = routeBuilder;

// UseRouting()
useRoutingFunc(builder);

// apply the next middleware
builder.Run(next);

return builder.Build();
}

return next;
}
}