在ASP.Net Core应用程序启动时,我有:
On an ASP.Net Core application startup I have:
RewriteOptions rewriteOptions = new RewriteOptions(); rewriteOptions.AddRedirectToHttps(); applicationBuilder.UseRewriter(rewriteOptions);在生产中,我需要将所有非WWW重定向到WWW Urls
When in Production I need to redirect all Non WWW to WWW Urls
例如:
domain/about > www.domain/about如何使用重写中间件来做到这一点?
How can I do this using Rewrite Middleware?
我认为可以使用AddRedirect和Regex完成此操作
I think this can be done using AddRedirect and Regex:
Github-ASP.NET Core重定向文档
但不确定如何做...
But not sure how to do it ...
推荐答案可重用的替代方法是创建自定义重写规则和相应的扩展方法,以将该规则添加到重写选项中.这与AddRedirectToHttps的工作原理非常相似.
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.
自定义规则:
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; } }扩展方法:
public static class RewriteOptionsExtensions { public static RewriteOptions AddRedirectToWww(this RewriteOptions options) { options.Rules.Add(new RedirectToWwwRule()); return options; } }用法:
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
更多推荐
使用Asp.Net Core中间件将非WWW重定向到WWW
发布评论