Last active
January 9, 2024 13:29
-
-
Save richarddewit/7f96efc43e99e28003c65130d6b79b20 to your computer and use it in GitHub Desktop.
Lowercase URLs in ASP.NET Core 6+
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
// Program.cs | |
// ... | |
builder.Services.AddControllersWithViews(); | |
// Use lowercase URLs | |
builder.Services.Configure<RouteOptions>(options => options.LowercaseUrls = true); | |
var app = builder.Build(); | |
// ... | |
app.UseHttpsRedirection(); | |
app.UseStaticFiles(); | |
// Enforce lowercase URLs by redirecting uppercase to lowercase | |
var rewriterOptions = new RewriteOptions().Add(new RedirectLowerCaseUrlsRule()); | |
app.UseRewriter(rewriterOptions); | |
app.UseRouting(); |
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
// Runes/RedirectLowercaseUrlRule.cs | |
using System.Net; | |
using Microsoft.AspNetCore.Rewrite; | |
using Microsoft.Net.Http.Headers; | |
namespace AppName.Rules; | |
public class RedirectLowerCaseUrlsRule : IRule | |
{ | |
public int StatusCode { get; } = (int)HttpStatusCode.MovedPermanently; | |
public void ApplyRule(RewriteContext context) | |
{ | |
HttpRequest request = context.HttpContext.Request; | |
PathString path = context.HttpContext.Request.Path; | |
HostString host = context.HttpContext.Request.Host; | |
if (path.HasValue && path.Value.Any(char.IsUpper) || host.HasValue && host.Value.Any(char.IsUpper)) | |
{ | |
HttpResponse response = context.HttpContext.Response; | |
response.StatusCode = StatusCode; | |
response.Headers[HeaderNames.Location] = (request.Scheme + "://" + host.Value + request.PathBase.Value + request.Path.Value).ToLower() + request.QueryString; | |
context.Result = RuleResult.EndResponse; | |
} | |
else | |
{ | |
context.Result = RuleResult.ContinueRules; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment