Last active
April 4, 2025 21:38
-
-
Save davecluderay/3b1de6f93488542bf33fb7b48c7f02c1 to your computer and use it in GitHub Desktop.
Register startup filter to insert PathBase middleware at the earliest opportunity
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Microsoft.Extensions.Options; | |
internal sealed class PathBaseSettings | |
{ | |
/// <summary> | |
/// The path prefix, if any, which will be stripped from the request path and added to the request path base. | |
/// During development, this might be empty, but then set when the application is deployed behind a reverse proxy. | |
/// Example: "/my-api" | |
/// </summary> | |
public string PathBase { get; set; } = string.Empty; | |
} | |
internal static class PathBaseStartupFilterExtensions | |
{ | |
/// <summary> | |
/// Adds a startup filter to register the path base middleware at the earliest possible point in the pipeline. | |
/// This means that path base will be applied before most other middleware (including routing). | |
/// </summary> | |
/// <remarks> | |
/// Based on: https://andrewlock.net/using-pathbase-with-dotnet-6-webapplicationbuilder/ | |
/// </remarks> | |
public static WebApplicationBuilder AddPathBaseStartupFilter(this WebApplicationBuilder builder) | |
{ | |
builder.Services.Configure<PathBaseSettings>(builder.Configuration); | |
builder.Services.AddTransient<IStartupFilter, PathBaseStartupFilter>(); | |
return builder; | |
} | |
} | |
file sealed class PathBaseStartupFilter : IStartupFilter | |
{ | |
private readonly string _pathBase; | |
public PathBaseStartupFilter(IOptions<PathBaseSettings> settings) | |
{ | |
_pathBase = settings.Value.PathBase; | |
} | |
public Action<IApplicationBuilder> Configure(Action<IApplicationBuilder> next) | |
{ | |
if (string.IsNullOrEmpty(_pathBase)) return next; | |
return builder => | |
{ | |
builder.UsePathBase(_pathBase); | |
next(builder); | |
}; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment