Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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 readonly ILogger _logger;
- private string _domain;
- private int _https_port;
- public WWWRedirectionMiddleware(RequestDelegate next, ILoggerFactory loggerFactory)
- {
- _next = next ?? throw new ArgumentNullException(nameof(next));
- _logger = loggerFactory.CreateLogger<WWWRedirectionMiddleware>();
- }
- 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.Invoke(context);
- }
- }
- }
Add Comment
Please, Sign In to add comment