James Law James Law - 1 month ago 6
C# Question

DotNetCore 1.0 MVC how to automatically redirect to a single domain in live

I have multiple domains for a website:

http://example.com

http://www.example.com

http://www.example.co.uk

In production, I want the primary domain to be http://www.example.com and for all other associated domains to be automatically redirected to the primary.

Historically I would've done this with URLRewrite, however I'm led to believe that doesn't exist in DotNetCore.

So... how would I do this?

Also, I don't want this to affect development environments.

Answer

An answer that works with DotNetCore 1.0 (also forces 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();
            }
        });
    }
}