A reusable alternative would be to create a custom rewrite rule and a corresponsing extension method to add the rule to the rewrite options. This would be very similar to how AddRedirectToHttps works.
Custom Rule:
public class RedirectToWwwRule : IRule
{
public virtual void ApplyRule(RewriteContext context)
{
var req = context.HttpContext.Request;
if (req.Host.Host.Equals("localhost", StringComparison.OrdinalIgnoreCase))
{
context.Result = RuleResult.ContinueRules;
return;
}
if (req.Host.Value.StartsWith("www.", StringComparison.OrdinalIgnoreCase))
{
context.Result = RuleResult.ContinueRules;
return;
}
var wwwHost = new HostString($"www.{req.Host.Value}");
var newUrl = UriHelper.BuildAbsolute(req.Scheme, wwwHost, req.PathBase, req.Path, req.QueryString);
var response = context.HttpContext.Response;
response.StatusCode = 301;
response.Headers[HeaderNames.Location] = newUrl;
context.Result = RuleResult.EndResponse;
}
}
Extension Method:
public static class RewriteOptionsExtensions
{
public static RewriteOptions AddRedirectToWww(this RewriteOptions options)
{
options.Rules.Add(new RedirectToWwwRule());
return options;
}
}
Usage:
var options = new RewriteOptions();
options.AddRedirectToWww();
options.AddRedirectToHttps();
app.UseRewriter(options);
Future versions of the rewrite middleware will contain the rule and the corresponding extension method. See this pull request
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…