Skip to content

Instantly share code, notes, and snippets.

@richarddewit
Last active January 9, 2024 13:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save richarddewit/7f96efc43e99e28003c65130d6b79b20 to your computer and use it in GitHub Desktop.
Save richarddewit/7f96efc43e99e28003c65130d6b79b20 to your computer and use it in GitHub Desktop.
Lowercase URLs in ASP.NET Core 6+
// 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();
// 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