summaryrefslogtreecommitdiff
path: root/src/SMAPI.Web/Framework/RewriteRules/ConditionalRewriteSubdomainRule.cs
diff options
context:
space:
mode:
authorJesse Plamondon-Willard <github@jplamondonw.com>2017-11-01 17:42:18 -0400
committerJesse Plamondon-Willard <github@jplamondonw.com>2017-11-01 17:42:18 -0400
commite0b72374cd14298aacc6f71dc391fdc9814be37c (patch)
tree2e5d85937c34539c1a0df48423b5136508693ca8 /src/SMAPI.Web/Framework/RewriteRules/ConditionalRewriteSubdomainRule.cs
parent79118316065a01322d8ea12a14589ec016794c32 (diff)
parent089e6de749ae7cb109af00164d2597c6644c255e (diff)
downloadSMAPI-e0b72374cd14298aacc6f71dc391fdc9814be37c.tar.gz
SMAPI-e0b72374cd14298aacc6f71dc391fdc9814be37c.tar.bz2
SMAPI-e0b72374cd14298aacc6f71dc391fdc9814be37c.zip
Merge branch 'develop' into stable
Diffstat (limited to 'src/SMAPI.Web/Framework/RewriteRules/ConditionalRewriteSubdomainRule.cs')
-rw-r--r--src/SMAPI.Web/Framework/RewriteRules/ConditionalRewriteSubdomainRule.cs48
1 files changed, 48 insertions, 0 deletions
diff --git a/src/SMAPI.Web/Framework/RewriteRules/ConditionalRewriteSubdomainRule.cs b/src/SMAPI.Web/Framework/RewriteRules/ConditionalRewriteSubdomainRule.cs
new file mode 100644
index 00000000..920632ab
--- /dev/null
+++ b/src/SMAPI.Web/Framework/RewriteRules/ConditionalRewriteSubdomainRule.cs
@@ -0,0 +1,48 @@
+using System;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Rewrite;
+
+namespace StardewModdingAPI.Web.Framework.RewriteRules
+{
+ /// <summary>Rewrite requests to prepend the subdomain portion (if any) to the path.</summary>
+ /// <remarks>Derived from <a href="https://stackoverflow.com/a/44526747/262123" />.</remarks>
+ internal class ConditionalRewriteSubdomainRule : IRule
+ {
+ /*********
+ ** Accessors
+ *********/
+ /// <summary>A predicate which indicates when the rule should be applied.</summary>
+ private readonly Func<HttpRequest, bool> ShouldRewrite;
+
+
+ /*********
+ ** Public methods
+ *********/
+ /// <summary>Construct an instance.</summary>
+ /// <param name="shouldRewrite">A predicate which indicates when the rule should be applied.</param>
+ public ConditionalRewriteSubdomainRule(Func<HttpRequest, bool> shouldRewrite = null)
+ {
+ this.ShouldRewrite = shouldRewrite ?? (req => true);
+ }
+
+ /// <summary>Applies the rule. Implementations of ApplyRule should set the value for <see cref="RewriteContext.Result" /> (defaults to RuleResult.ContinueRules).</summary>
+ /// <param name="context">The rewrite context.</param>
+ public void ApplyRule(RewriteContext context)
+ {
+ HttpRequest request = context.HttpContext.Request;
+
+ // check condition
+ if (!this.ShouldRewrite(request))
+ return;
+
+ // get host parts
+ string host = request.Host.Host;
+ string[] parts = host.Split('.');
+ if (parts.Length < 2)
+ return;
+
+ // prepend to path
+ request.Path = $"/{parts[0]}{request.Path}";
+ }
+ }
+}