using System; using System.Net; using Microsoft.AspNetCore.Rewrite; namespace StardewModdingAPI.Web.Framework.RedirectRules { /// Redirect hostnames to a URL if they match a condition. internal class RedirectHostsToUrlsRule : RedirectMatchRule { /********* ** Fields *********/ /// Maps a lowercase hostname to the resulting redirect URL. private readonly Func Map; /********* ** Public methods *********/ /// Construct an instance. /// The status code to use for redirects. /// Hostnames mapped to the resulting redirect URL. public RedirectHostsToUrlsRule(HttpStatusCode statusCode, Func map) { this.StatusCode = statusCode; this.Map = map ?? throw new ArgumentNullException(nameof(map)); } /********* ** Private methods *********/ /// Get the new redirect URL. /// The rewrite context. /// Returns the redirect URL, or null if the redirect doesn't apply. protected override string? GetNewUrl(RewriteContext context) { // get requested host string? host = context.HttpContext.Request.Host.Host; // get new host host = this.Map(host); if (host == null) return null; // rewrite URL UriBuilder uri = this.GetUrl(context.HttpContext.Request); uri.Host = host; return uri.ToString(); } } }