Search code examples
http-redirectasp.net-core-2.0lowercase

Redirect asp.net core 2.0 urls to lowercase


I have seen that you can configure routing in ASP.NET Core 2.0 to generate lower case urls as described here: https://stackoverflow.com/a/45777372/83825

Using this:

services.AddRouting(options => options.LowercaseUrls = true);

However, although this is fine to GENERATE the urls, it doesn't appear to do anything to actually ENFORCE them, that is, redirect any urls that are NOT all lowercase to the corresponding lowercase url (preferably via 301 redirect).

I know people are accessing my site via differently cased urls, and I want them to all be lowercase, permanently.

Is doing a standard redirect via RewriteOptions and Regex the only way to do this? what would be the appropriate expression to do this:

var options = new RewriteOptions().AddRedirect("???", "????");

Or is there another way?


Solution

  • I appreciate this is many months old, however for people who may be looking for the same solution, you can add a complex redirect implementing IRule such as:

    public class RedirectLowerCaseRule : 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;
            } 
        }
    }
    

    This can then be applied in your Startup.cs under Configure method as such:

    new RewriteOptions().Add(new RedirectLowerCaseRule());