如何使用RewriteMiddleware将www重定向到AspNetCore 1.1预览1中的非www规则?

Fab*_*NET 9 c# .net-core asp.net-core

使用AspNetCore 1.1位和新的RewriteMiddleware我写了这样的东西Startup.cs来处理www到非www重定向:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    var options = new RewriteOptions()
        .AddRedirect("(www\\.)(.*)", "$1");

    app.UseRewriter(options);

    // Code removed for brevty
}
Run Code Online (Sandbox Code Playgroud)

由于RedirectRule仅适用于路径而不是整个请求uri,因此正则表达式不匹配.

如何使用相同的方法将www重定向到非www规则?我不想使用IISUrlRewriteRule.

nat*_*ter 13

RewriteOptions允许您添加自定义规则实现.如您所述,预先编写的规则不支持重定向主机名.但是,这并不难实现.

例:

public class NonWwwRule : IRule
{
    public void ApplyRule(RewriteContext context)
    {
        var req = context.HttpContext.Request;
        var currentHost = req.Host;
        if (currentHost.Host.StartsWith("www."))
        {
            var newHost = new HostString(currentHost.Host.Substring(4), currentHost.Port ?? 80);
            var newUrl = new StringBuilder().Append("http://").Append(newHost).Append(req.PathBase).Append(req.Path).Append(req.QueryString);
            context.HttpContext.Response.Redirect(newUrl.ToString());
            context.Result = RuleResult.EndResponse;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

您可以将其添加到RewriteOptions上的Rules集合中.

        var options = new RewriteOptions();
        options.Rules.Add(new NonWwwRule());

        app.UseRewriter(options);
Run Code Online (Sandbox Code Playgroud)