1

我剛剛安裝在我的主機上的SSL證書,並以爲我會所有的HTTP流量重定向到https。我發現在.net內核中有一個新的軟件包可以幫助它。asp.net核心重定向http流量到https的問題

的問題是,它並沒有爲我工作,我想不通爲什麼。當我嘗試導航到http://mysite.co.uk測試與消息失敗重定向說

的網頁沒有正確重定向 的Firefox已經檢測到服務器重定向的方式爲這個地址的請求,將永遠不會完成。 這個問題有時可以通過禁用或拒絕接受Cookie引起的。

這裏是我的stratup.cs:

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<Startup>(); 
     } 

     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<ApplicationDbContext>(options => 
      options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); 

     services.AddIdentity<ApplicationUser, IdentityRole>(
      config => 
      { 
       config.SignIn.RequireConfirmedEmail = true; 
      }) 
      .AddEntityFrameworkStores<ApplicationDbContext>() 
      .AddDefaultTokenProviders(); 

     services.Configure<GzipCompressionProviderOptions> 
      (options => options.Level = CompressionLevel.Optimal); 
      services.AddResponseCompression(options => 
      { 
       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<GzipCompressionProvider>(); 
      }); 

     services.AddMvc(); 


     // Add application services. 
     services.Configure<SmtpConfig>(optionsSetup => 
     { 
      //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<RecaptchaConfig>(optionsSetup => 
     { 
      //get from config.json file 
      optionsSetup.RecaptchaPublicKey = Configuration["Recaptcha:PublicKey"]; 
      optionsSetup.RecaptchaPrivateKey = Configuration["Recaptcha:PrivateKey"]; 
     }); 
     // Add default bootstrap-styled pager implementation 
     services.AddBootstrapPagerGenerator(options => 
     { 
      // Use default pager options. 
      options.ConfigureDefault(); 
     }); 
     services.AddTransient<IEmailSender, AuthMessageSender>(); 
     services.AddTransient<ISmsSender, AuthMessageSender>(); 
     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 => 
      { 
       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 => 
     { 
      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<UserManager<ApplicationUser>>(); 
     var RoleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>(); 
     // Create a list of roles with both name and normalised name attributes 
     List<IdentityRole> roles = new List<IdentityRole> 
     { 
      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("[email protected]"); 
     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"); 
      } 
     } 
    } 
} 
} 

我加入到配置的片段是:

 app.UseRewriter(new RewriteOptions() 
     .AddRedirectToHttps()); 

它採用Microsoft.AspNetCore.Rewrite;

我剛纔用鍍鉻進行檢查,並顯示重複的重定向,並且不能因「ERR_TOO_MANY_REDIRECTS」這樣的東西導致一個循環。

有沒有一種方法來檢查,如果該請求已經是「https」開頭,或者是有另一種方式我可以做的事情?

回答

0

我可以用下面的解決了類似的問題:

if (env.IsProduction()) 
{ 
    app.UseRewriter(new RewriteOptions().AddRedirectToHttpsPermanent()); 
} 
+0

我希望有:)但遺憾的是,它仍然有相同的錯誤。它是重定向的,這是我想的,但有些東西我錯過了某處。 –

0

花費一整天時間來排序了這一點後,加入[RequireHttps]屬性,嘗試各種片段中,我發現谷歌搜索的問題,試圖傳遞標題......最後,我訴諸了我之前嘗試過的一些似乎沒有奏效的東西。我編輯的web.config文件是在服務器上(我不知道如何做到這一點的發佈)增加以下內容:

<system.webServer> 
    <rewrite> 
     <rules> 
     <rule name="HTTP/S to HTTPS Redirect" enabled="true" stopProcessing="true"> 
      <match url="(.*)" /> 
      <conditions logicalGrouping="MatchAny"> 
       <add input="{SERVER_PORT_SECURE}" pattern="^0$" /> 
      </conditions> 
      <action type="Redirect" url="https://{HTTP_HOST}/{R:1}" redirectType="Permanent" /> 
     </rule> 
     </rules> 
    </rewrite> 
    </system.webServer> 

從這裏評論摘自:https://github.com/aspnet/KestrelHttpServer/issues/916

從我已經閱讀,它與Kestrel做了什麼,但我不完全確定是什麼:D,但它的工作原理!每次發佈都必須改變這一點很煩人,所以明天我會試着弄清楚每次這樣做可以爲我做些什麼。