James Law James Law - 1 year ago 71
C# Question

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

I have multiple domains for a website:




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 Source

An answer that works with DotNetCore 1.0 (also forces https)


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;
            else if (!context.Request.IsHttps)
                var withHttps = "https://" + context.Request.Host + context.Request.Path;
                await next();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download