From 22965604bfa5858a089d842173cdebe6aaed0ed8 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Mon, 9 Apr 2018 19:30:17 -0400 Subject: add support for build message URLs (#471) --- .../Framework/RewriteRules/RedirectToUrlRule.cs | 20 ++++++++------------ 1 file changed, 8 insertions(+), 12 deletions(-) (limited to 'src/SMAPI.Web/Framework/RewriteRules') diff --git a/src/SMAPI.Web/Framework/RewriteRules/RedirectToUrlRule.cs b/src/SMAPI.Web/Framework/RewriteRules/RedirectToUrlRule.cs index 0719e311..4bae0b4c 100644 --- a/src/SMAPI.Web/Framework/RewriteRules/RedirectToUrlRule.cs +++ b/src/SMAPI.Web/Framework/RewriteRules/RedirectToUrlRule.cs @@ -12,11 +12,8 @@ namespace StardewModdingAPI.Web.Framework.RewriteRules /********* ** Properties *********/ - /// A predicate which indicates when the rule should be applied. - private readonly Func ShouldRewrite; - - /// The new URL to which to redirect. - private readonly string NewUrl; + /// Get the new URL to which to redirect (or null to skip). + private readonly Func NewUrl; /********* @@ -27,8 +24,7 @@ namespace StardewModdingAPI.Web.Framework.RewriteRules /// The new URL to which to redirect. public RedirectToUrlRule(Func shouldRewrite, string url) { - this.ShouldRewrite = shouldRewrite ?? (req => true); - this.NewUrl = url; + this.NewUrl = req => shouldRewrite(req) ? url : null; } /// Construct an instance. @@ -37,8 +33,7 @@ namespace StardewModdingAPI.Web.Framework.RewriteRules public RedirectToUrlRule(string pathRegex, string url) { Regex regex = new Regex(pathRegex, RegexOptions.IgnoreCase | RegexOptions.Compiled); - this.ShouldRewrite = req => req.Path.HasValue && regex.IsMatch(req.Path.Value); - this.NewUrl = url; + this.NewUrl = req => req.Path.HasValue ? regex.Replace(req.Path.Value, url) : null; } /// Applies the rule. Implementations of ApplyRule should set the value for (defaults to RuleResult.ContinueRules). @@ -47,14 +42,15 @@ namespace StardewModdingAPI.Web.Framework.RewriteRules { HttpRequest request = context.HttpContext.Request; - // check condition - if (!this.ShouldRewrite(request)) + // check rewrite + string newUrl = this.NewUrl(request); + if (newUrl == null || newUrl == request.Path.Value) return; // redirect request HttpResponse response = context.HttpContext.Response; response.StatusCode = (int)HttpStatusCode.Redirect; - response.Headers["Location"] = this.NewUrl; + response.Headers["Location"] = newUrl; context.Result = RuleResult.EndResponse; } } -- cgit