I wrote a small middleware for redirecting between WWW URLs.
The most important thing that I want to change is to make it super fast.
Here's what it is doing:
If the host is localhost or mywebsite.com without any subdomains and without www, it will redirect to www.localhost or www.mywebsite.com.
If the host starts with www. AND has subdomains, it will redirect to a url without www.
using System;
using System.Threading.Tasks;
using System.Text.RegularExpressions;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Extensions;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Logging;
namespace Website.Middlewares
{
public class WWWRedirectionMiddleware
{
private readonly RequestDelegate _next;
private string _domain;
private int _https_port;
public WWWRedirectionMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context)
{
var request = context.Request;
var response = context.Response;
var host = request.Host;
if (Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") == "Development")
{
_domain = "localhost";
_https_port = 5001;
}
else
{
_domain = "seaoftools.com";
_https_port = 80;
}
// Redirect to www domain if url is home page
if (host.Host.Equals(_domain, StringComparison.OrdinalIgnoreCase))
{
host = new HostString("www." + host.Host, _https_port);
var redirectUrl = UriHelper.BuildAbsolute(
"https",
host,
request.PathBase,
request.Path,
request.QueryString);
response.Redirect(redirectUrl, true);
return;
} // Redirect to non-www domain if url is with a subdomain
else if (host.Value.StartsWith("www.", StringComparison.OrdinalIgnoreCase)
&& Regex.Replace(host.Host, @"www.|" + _domain, String.Empty) != String.Empty)
{
host = new HostString(host.Host.Replace("www.", String.Empty), _https_port);
var redirectUrl = UriHelper.BuildAbsolute(
"https",
host,
request.PathBase,
request.Path,
request.QueryString);
response.Redirect(redirectUrl, true);
return;
}
await _next(context);
}
}
}
What should I change to make the middleware run faster?