Sunday, September 17, 2017

URL rewrite for https and www in ASPNET Core (Solved)

If you want to url rewrite to both https and www using ASP.NET Core 2.0, here is some pretty straight-forward C# you can add to your Startup.cs.

Woo-hoo!

// ...

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        // ...
    }
    else
    {
        // url rewrite; do this before UseStaticFiles
        var options = new RewriteOptions().Add(
            new RedirectRules(rewriteHttps: true, rewriteWww: true));
        app.UseRewriter(options);
    }

    // ...
}

// ...

public class RedirectRules : Microsoft.AspNetCore.Rewrite.IRule
{
    private readonly bool _rewriteHttps;
    private readonly bool _rewriteWww;

    public RedirectRules(bool rewriteHttps, bool rewriteWww)
    {
        _rewriteHttps = rewriteHttps;
        _rewriteWww = rewriteWww;
    }

    public void ApplyRule(RewriteContext context)
    {
        //
        // redirect two ways
        //    - http to https (if enabled)
        //    - non-www host to www host (if enabled)
        //

        const string hostRoot = "mydomain.com";
        var request = context.HttpContext.Request;
        var currentHost = request.Host;
        HostString newHost;

        // do we need to rewrite from http to https
        var isNewProtocol = _rewriteHttps && request.Scheme.ToLower() == "http";

        // do we need to rewrite from non-www host to www host
        if (_rewriteWww && currentHost.Host == hostRoot)
            newHost = new HostString($"www.{hostRoot}", currentHost.Port ?? 80);

        // if either rewrite done, create a new url
        if (isNewProtocol || newHost.HasValue)
        {
            var newUrl = new StringBuilder()
                .Append(isNewProtocol ? "https" : request.Scheme)
                .Append("://")
                .Append(newHost.HasValue ? newHost : currentHost)
                .Append(request.PathBase)
                .Append(request.Path)
                .Append(request.QueryString);
            context.HttpContext.Response.Redirect(newUrl.ToString(), permanent: true);
            context.Result = RuleResult.EndResponse;
        }
    }
}

Can't RDP? How to enable / disable virtual machine firewall for Azure VM

Oh no!  I accidentally blocked the RDP port on an Azure virtual machine which resulted in not being able to log into the VM anymore.  I did ...