title: asp.net core redirect http traffic to https issue
body: <p>I have just installed an ssl certificate on my host, and thought I would redirect all http traffic to https.  I found that there is a new package for helping with it in .net core.</p>
  
  <p>The problem is that it doesn't work for me and I can't figure out why.  When I try to navigate to <a href="http://mysite.co.uk" rel="nofollow noreferrer">http://mysite.co.uk</a> to test the redirection it fails with a message saying</p>
  
  <blockquote>
    <p>The page isn't redirecting properly
    Firefox has detected that the server is redirecting the request for this address in a way that will never complete.
    This problem can sometimes be caused by disabling or refusing to accept cookies.</p>
  </blockquote>
  
  <p>Here is my stratup.cs:</p>
  
  <pre><code>using System;
  using System.Collections.Generic;
  using System.Threading.Tasks;
  using Microsoft.AspNetCore.Builder;
  using Microsoft.AspNetCore.Hosting;
  using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
  using Microsoft.EntityFrameworkCore;
  using Microsoft.Extensions.Configuration;
  using Microsoft.Extensions.DependencyInjection;
  using Microsoft.Extensions.Logging;
  using Playabout.Data;
  using Playabout.Models;
  using Playabout.Services;
  using Microsoft.AspNetCore.Identity;
  using System.Security.Claims;
  using Microsoft.AspNetCore.Localization;
  using Microsoft.Net.Http.Headers;
  using System.Globalization;
  using Sakura.AspNetCore.Mvc;
  using Microsoft.AspNetCore.ResponseCompression;
  using System.IO.Compression;
  using System.Linq;
  using Microsoft.AspNetCore.Rewrite;
  using System.Net;
  
  namespace Playabout
  {
  public class Startup
  {
      public Startup(IHostingEnvironment env)
      {
          var builder = new ConfigurationBuilder()
              .SetBasePath(env.ContentRootPath)
              .AddJsonFile("appsettings.json", optional: false,     reloadOnChange: true)
              .AddJsonFile($"appsettings.{env.EnvironmentName}.json",     optional: true);
  
          if (env.IsDevelopment())
          {
              // For more details on using the user secret store see http://go.microsoft.com/fwlink/?LinkID=532709
              //builder.AddUserSecrets&lt;Startup&gt;();
          }
  
          builder.AddEnvironmentVariables();
          Configuration = builder.Build();
      }
  
      public IConfigurationRoot Configuration { get; }
  
      // This method gets called by the runtime. Use this method to add services to the container.
      public void ConfigureServices(IServiceCollection services)
      {
          // Add framework services.
          services.AddDbContext&lt;ApplicationDbContext&gt;(options =&gt;
              options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
  
          services.AddIdentity&lt;ApplicationUser, IdentityRole&gt;(
              config =&gt;
              {
                  config.SignIn.RequireConfirmedEmail = true;
              })
              .AddEntityFrameworkStores&lt;ApplicationDbContext&gt;()
              .AddDefaultTokenProviders();
  
          services.Configure&lt;GzipCompressionProviderOptions&gt;
              (options =&gt; options.Level = CompressionLevel.Optimal);
              services.AddResponseCompression(options =&gt;
              {
                  options.MimeTypes = ResponseCompressionDefaults.MimeTypes.Concat(new[]
                  {
                      "text/plain",
                      "text/css",
                      "application/javascript",
                      "text/html",
                      "application/xml",
                      "text/xml",
                      "application/json",
                      "text/json",
                      // Custom
                      "text/javascript",
                      "image/svg+xml"
                  });
                  options.Providers.Add&lt;GzipCompressionProvider&gt;();
              });
  
          services.AddMvc();
  
  
          // Add application services.
          services.Configure&lt;SmtpConfig&gt;(optionsSetup =&gt;
          {
              //get from config.json file
              optionsSetup.EmailDisplayName = Configuration["SMTP:DisplayName"];
              optionsSetup.SmtpPassworrd = Configuration["SMTP:Password"];
              optionsSetup.SmtpUserEmail = Configuration["SMTP:Email"];
              optionsSetup.SmtpHost = Configuration["SMTP:Host"];
              optionsSetup.SmtpPort = Convert.ToInt32(Configuration["SMTP:Port"]);
          });
          services.Configure&lt;RecaptchaConfig&gt;(optionsSetup =&gt;
          {
              //get from config.json file
              optionsSetup.RecaptchaPublicKey = Configuration["Recaptcha:PublicKey"];
              optionsSetup.RecaptchaPrivateKey = Configuration["Recaptcha:PrivateKey"];
          });
          // Add default bootstrap-styled pager implementation
          services.AddBootstrapPagerGenerator(options =&gt;
          {
              // Use default pager options.
              options.ConfigureDefault();
          });
          services.AddTransient&lt;IEmailSender, AuthMessageSender&gt;();
          services.AddTransient&lt;ISmsSender, AuthMessageSender&gt;();
          services.AddSession();
      }
  
      // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
      public async void Configure(IApplicationBuilder app, IHostingEnvironment env,
          ILoggerFactory loggerFactory, IServiceProvider serviceProvider, ApplicationDbContext context)
      {
          loggerFactory.AddConsole(Configuration.GetSection("Logging"));
          loggerFactory.AddDebug();
  
          if (env.IsDevelopment())
          {
              app.UseDeveloperExceptionPage();
              app.UseDatabaseErrorPage();
              app.UseBrowserLink();
          }
          else
          {
              app.UseExceptionHandler("/Home/Error");
          }
          var supportedCultures = new[]
          {
              new CultureInfo("en-GB"),
  
          };
          app.UseRequestLocalization(new RequestLocalizationOptions
          {
              DefaultRequestCulture = new RequestCulture("en-GB"),
              SupportedCultures = supportedCultures,
              SupportedUICultures = supportedCultures
          });
          app.UseRewriter(new RewriteOptions()
              .AddRedirectToHttps());
          app.UseResponseCompression();
          app.UseStaticFiles(new StaticFileOptions
          {
              OnPrepareResponse = ctx =&gt;
              {
                  const int durationInSeconds = 60 * 60 * 730;
                  ctx.Context.Response.Headers[HeaderNames.CacheControl] =
                      "public,max-age=" + durationInSeconds;
              }
          });
  
          app.UseSession();
          app.UseIdentity();
  
          // Add external authentication middleware below. To configure them please see http://go.microsoft.com/fwlink/?LinkID=532715
          app.UseFacebookAuthentication(new FacebookOptions()
          {
              AppId = Configuration["Authentication:Facebook:AppId"],
              AppSecret = Configuration["Authentication:Facebook:AppSecret"]
          });
          app.UseGoogleAuthentication(new GoogleOptions()
          {
              ClientId = Configuration["Authentication:Google:ClientId"],
              ClientSecret = Configuration["Authentication:Google:ClientSecret"]
          });
  
          app.UseMvc(routes =&gt;
          {
              routes.MapRoute(
                  name: "default",
                  template: "{controller=Home}/{action=Index}/{id?}");
          });
  
          try
          {
              await CreateRoles(context, serviceProvider);
          }
          catch (Exception)
          { }
      }
      private async Task CreateRoles(ApplicationDbContext context, IServiceProvider serviceProvider)
      {
          var userManager = serviceProvider.GetRequiredService&lt;UserManager&lt;ApplicationUser&gt;&gt;();
          var RoleManager = serviceProvider.GetRequiredService&lt;RoleManager&lt;IdentityRole&gt;&gt;();
          // Create a list of roles with both name and normalised name attributes
          List&lt;IdentityRole&gt; roles = new List&lt;IdentityRole&gt;
          {
              new IdentityRole { Name = "Admin", NormalizedName = "ADMIN" },
              new IdentityRole { Name = "Member", NormalizedName = "MEMBER" },
              new IdentityRole { Name = "Moderator", NormalizedName = "MODERATOR" }
          };
          // Check if the role already exists
          foreach (var role in roles)
          {
              var roleExist = await RoleManager.RoleExistsAsync(role.Name);
              if (!roleExist)
              {   // Add it if it doesn't
                  context.Roles.Add(role);
                  context.SaveChanges();
              }
          }
          var user = await userManager.FindByEmailAsync("markperry.uk@gmail.com");
          if (user != null)
          {
              var gotRoles = userManager.GetRolesAsync(user);
              if (!gotRoles.Equals("Admin"))
              {
                  await userManager.AddToRoleAsync(user, "Admin");
              }
          }
          else if (user == null)
          {
              var nuser = new ApplicationUser
              {
                  FirstName = Configuration["AppSettings:Admin:FirstName"],
                  LastName = Configuration["AppSettings:Admin:LastName"],
                  PhoneNumber = Configuration["AppSettings:Admin:PhoneNumber"],
                  UserName = Configuration["AppSettings:Admin:UserName"],
                  Email = Configuration["AppSettings:Admin:Email"],
                  JoinDate = DateTime.Now,
                  EmailConfirmed = true,
                  PhoneNumberConfirmed = true
              };
              var result = await userManager.CreateAsync(nuser, Configuration["AppSettings:Admin:Password"]);
              if (result.Succeeded)
              {
                  await userManager.AddClaimAsync(nuser, new Claim("GivenName", nuser.FirstName));
                  await userManager.AddClaimAsync(nuser, new Claim("Surname", nuser.LastName));
                  await userManager.AddToRoleAsync(nuser, "Admin");
              }
          }
      }
  }
  }
  </code></pre>
  
  <p>The snippet I added to configure is:</p>
  
  <pre><code>        app.UseRewriter(new RewriteOptions()
          .AddRedirectToHttps());
  </code></pre>
  
  <p>which uses Microsoft.AspNetCore.Rewrite;</p>
  
  <p>I have just used chrome to inspect, and that shows repeated redirects, and fails due to "ERR_TOO_MANY_REDIRECTS" so something is causing a loop.</p>
  
  <p>Is there a way to check if the request is already "https", or is there another way I can do things?</p>