DotNetCore 1.0 MVC如何在直播中自动重定向到单个域

Jam*_*Law 4 c# asp.net-mvc asp.net-core-mvc .net-core

我的网站有多个域:

http://example.com

http://www.example.com

http://www.example.co.uk

在生产中,我希望主域为http://www.example.com,并且所有其他关联域都自动重定向到主域。

从历史上看,我会使用 URLRewrite 来完成此操作,但我相信 DotNetCore 中不存在这种情况。

那么...我该怎么做呢?

另外,我不希望这影响开发环境。

Jam*_*Law 5

适用于 DotNetCore 1.0 的答案(也强制使用 https)

Startup.cs

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    // Other configuration code here...

    if (env.IsProduction())
    {
        app.Use(async (context, next) =>
        {
            if (context.Request.Host != new HostString("www.example.com"))
            {
                var withDomain = "https://www.example.com" + context.Request.Path;
                context.Response.Redirect(withDomain);
            }
            else if (!context.Request.IsHttps)
            {
                var withHttps = "https://" + context.Request.Host + context.Request.Path;
                context.Response.Redirect(withHttps);
            }
            else
            {
                await next();
            }
        });
    }
}
Run Code Online (Sandbox Code Playgroud)