ASP.NET Core 1.1中新URL重写中间件的文档说:“例如,您可以通过将对http://example.com的任何请求重写为http://www.example.com来确保规范主机名”。不幸的是,这个例子的代码没有显示,因为这正是我想要做的。
示例如下所示......
var options = new RewriteOptions()
.AddRedirect("(.*)/", "$1");
这使用正则表达式将具有尾部斜杠的任何请求重定向到不具有尾部斜杠的URL。我需要的是相当于“重定向到www。*”,如果它还没有。
我能够通过创建自定义IRule实现来实现这一目标:
public class RedirectToWwwRule : IRule
{
public virtual void ApplyRule(RewriteContext context)
{
var host = context.HttpContext.Request.Host;
if (host.HasValue && !host.Value.StartsWith("www")) {
var req = context.HttpContext.Request;
var response = context.HttpContext.Response;
var newUrl = new StringBuilder()
.Append("https://www.").Append(host)
.Append(req.PathBase).Append(req.Path).Append(req.QueryString);
context.HttpContext.Response.Redirect(newUrl.ToString(), true);
}
}
}
我很难编码“https://”但在我的情况下这没关系。我认为必须有一种更简单的方法来做到这一点。