简体   繁体   中英

How to force all URLs to lowercase in ASP.NET Core 2.2 and newer version?

I want to convert all URLs to lowercase.

For example:

  • https://ABC123.com/ -> https://abc123.com/
  • https://StackoverFlow.com/ -> https://stackoverflow.com/

Thanks in advance

Do you want to force all URL to lowercase in browser? If it is, You can add

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

in your startup.cs class.

在此处输入图像描述

I have added 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());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM