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 : LowercaseUrls property on the RouteCollection class has introduced in ASP . NET 4.5. Using this property we can lowercase all of our URLs.
In a browser with developer tools enabled, make a request to the sample app with the path /redirect-rule/1234/5678 . The regular expression matches the request path on redirect-rule/(. *) , and the path is replaced with /redirected/1234/5678 . The redirect URL is sent back to the client with a 302 - Found status code.
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 + request.Path).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());
Hope this helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With