Add option to ignore trailing slashes in requests

This commit is contained in:
GHXX 2025-06-02 17:23:35 +02:00
parent 6ad805841d
commit d2a3a82b95
2 changed files with 11 additions and 2 deletions

View File

@ -213,7 +213,7 @@ public sealed class HttpServer {
private readonly Dictionary<Type, IParameterConverter> stringToTypeParameterConverters = new(); private readonly Dictionary<Type, IParameterConverter> stringToTypeParameterConverters = new();
private static string NormalizeUrlPath(string url) { private string NormalizeUrlPath(string url) {
var fwdSlashUrl = url.Replace('\\', '/'); var fwdSlashUrl = url.Replace('\\', '/');
var segments = fwdSlashUrl.Trim('/').Split('/', StringSplitOptions.RemoveEmptyEntries).ToList(); var segments = fwdSlashUrl.Trim('/').Split('/', StringSplitOptions.RemoveEmptyEntries).ToList();
@ -242,7 +242,12 @@ public sealed class HttpServer {
} }
rv.AppendJoin('/', simplifiedSegmentsReversed.Reverse<string>()); rv.AppendJoin('/', simplifiedSegmentsReversed.Reverse<string>());
return '/' + (rv.ToString().TrimEnd('/') + (fwdSlashUrl.EndsWith('/') ? "/" : "")).TrimStart('/'); var suffix = (rv.ToString().TrimEnd('/') + (fwdSlashUrl.EndsWith('/') ? "/" : "")).TrimStart('/');
if (conf.TrimTrailingSlash) {
suffix = suffix.TrimEnd('/');
}
return '/' + suffix;
} }
private async Task ProcessRequestAsync(HttpListenerContext ctx) { private async Task ProcessRequestAsync(HttpListenerContext ctx) {

View File

@ -13,6 +13,10 @@ public class SimpleHttpServerConfiguration {
/// See description of <see cref="DisableLogMessagePrinting"/> /// See description of <see cref="DisableLogMessagePrinting"/>
/// </summary> /// </summary>
public CustomLogMessageHandler? LogMessageHandler { get; init; } = null; public CustomLogMessageHandler? LogMessageHandler { get; init; } = null;
/// <summary>
/// If set to true, paths ending with / are identical to paths without said trailing slash. E.g. /index is then the same as /index/
/// </summary>
public bool TrimTrailingSlash { get; init; } = true;
public SimpleHttpServerConfiguration() { } public SimpleHttpServerConfiguration() { }