using System;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Rewrite;
namespace StardewModdingAPI.Web.Framework.RewriteRules
{
/// Rewrite requests to prepend the subdomain portion (if any) to the path.
/// Derived from .
internal class ConditionalRewriteSubdomainRule : IRule
{
/*********
** Accessors
*********/
/// A predicate which indicates when the rule should be applied.
private readonly Func ShouldRewrite;
/*********
** Public methods
*********/
/// Construct an instance.
/// A predicate which indicates when the rule should be applied.
public ConditionalRewriteSubdomainRule(Func shouldRewrite = null)
{
this.ShouldRewrite = shouldRewrite ?? (req => true);
}
/// 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;
// 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}";
}
}
}