From 13baaf8920f4a80ac3c0cd41a16b9afb1b993048 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Sun, 29 Oct 2017 22:18:08 -0400 Subject: add smapi.io shortcut URLs (#375) --- .../Framework/RewriteRules/RedirectToUrlRule.cs | 61 ++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 src/SMAPI.Web/Framework/RewriteRules/RedirectToUrlRule.cs (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 new file mode 100644 index 00000000..0719e311 --- /dev/null +++ b/src/SMAPI.Web/Framework/RewriteRules/RedirectToUrlRule.cs @@ -0,0 +1,61 @@ +using System; +using System.Net; +using System.Text.RegularExpressions; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Rewrite; + +namespace StardewModdingAPI.Web.Framework.RewriteRules +{ + /// Redirect requests to an external URL if they match a condition. + internal class RedirectToUrlRule : IRule + { + /********* + ** 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; + + + /********* + ** Public methods + *********/ + /// Construct an instance. + /// A predicate which indicates when the rule should be applied. + /// The new URL to which to redirect. + public RedirectToUrlRule(Func shouldRewrite, string url) + { + this.ShouldRewrite = shouldRewrite ?? (req => true); + this.NewUrl = url; + } + + /// Construct an instance. + /// A case-insensitive regex to match against the path. + /// The external URL. + 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; + } + + /// Applies the rule. Implementations of ApplyRule should set the value for (defaults to RuleResult.ContinueRules). + /// The rewrite context. + public void ApplyRule(RewriteContext context) + { + HttpRequest request = context.HttpContext.Request; + + // check condition + if (!this.ShouldRewrite(request)) + return; + + // redirect request + HttpResponse response = context.HttpContext.Response; + response.StatusCode = (int)HttpStatusCode.Redirect; + response.Headers["Location"] = this.NewUrl; + context.Result = RuleResult.EndResponse; + } + } +} -- cgit