在ASP.Net Core应用程序启动中,我有:
RewriteOptions rewriteOptions = new RewriteOptions();
rewriteOptions.AddRedirectToHttps();
applicationBuilder.UseRewriter(rewriteOptions);
在制作时,我需要将所有非WWW重定向到WWW。
例如:
domain.com/contact > www.domain.com/contact
如何使用重写中间件执行此操作?
答案 0 :(得分:5)
您可以通过创建类并实现IRule
接口来创建自定义规则(请参阅下文)。我认为必须有更好的方法来构建redirectUrl
。
public class CanonicalDomainRewriteRule : IRule
{
public void ApplyRule(RewriteContext context)
{
HttpRequest request = context.HttpContext.Request;
if (request.Host.Value.StartsWith("www.", StringComparison.OrdinalIgnoreCase))
{
return;
}
else
{
HttpResponse response = context.HttpContext.Response;
string redirectUrl = $"{request.Scheme}://www.{request.Host}{request.Path}{request.QueryString}";
response.Headers[HeaderNames.Location] = redirectUrl;
response.StatusCode = StatusCodes.Status301MovedPermanently;
context.Result = RuleResult.EndResponse;
}
}
}
您可以在ConfigureServices
方法中添加以下规则:
RewriteOptions rewriteOptions = new RewriteOptions()
.Add(new CanonicalDomainRewriteRule());
app.UseRewriter(rewriteOptions);
有关更多示例,请参阅Extensions and Options: IRule-based rule。