首页 > 解决方案 > 如何在 ASP.NET Core 中强制执行 HTTPS

问题描述

我已经安装了LetsEncrypt,它在 http 和 https 中也能正常工作,但我尝试在 ASP.NET Core 中强制重定向 HTTPS 作为docs.microsoft,我使用 asp.net core 2.2iis 10.0.14393.0 这是我的管道配置:

 services.Configure<CookiePolicyOptions>(options =>
         {

             options.CheckConsentNeeded = context => true;
             options.MinimumSameSitePolicy = SameSiteMode.None;
         });
        services.AddAuthentication(option =>
        {
           ..

        }).AddCookie(option =>
        {
            option.AccessDeniedPath = "/Account/Denied";
            option.LoginPath = "/Account/Login";
            ...


        });
        services.AddHttpsRedirection(options =>

        {

            options.RedirectStatusCode = StatusCodes.Status308PermanentRedirect;
            options.HttpsPort = 443;

        });
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

并在配置方法中:

  if (env.IsDevelopment())
        {

            app.UseDeveloperExceptionPage();
            app.UseDatabaseErrorPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }
        app.UseHttpsRedirection();
        app.UseAuthentication();
        app.UseStaticFiles(new StaticFileOptions()
        {
            OnPrepareResponse = context =>
            {
                context.Context.Response.Headers["Cache-Control"] =
                        "private, max-age=43200";

                context.Context.Response.Headers["Expires"] =
                        DateTime.UtcNow.AddDays(30).ToString("R");
            }
        });
        app.UseCookiePolicy();
        app.Use(async (context, next) =>
        {
            // For GetTypedHeaders, add: using Microsoft.AspNetCore.Http;
            context.Response.GetTypedHeaders().CacheControl =
                new Microsoft.Net.Http.Headers.CacheControlHeaderValue()
                {
                    Public = true,
                    MaxAge = TimeSpan.FromDays(30)
                };
            context.Response.Headers[Microsoft.Net.Http.Headers.HeaderNames.Vary] =
                new string[] { "Accept-Encoding" };

            await next();
        });
        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });

但我在 Firefox 中遇到了这个错误:

页面未正确重定向

我哪里错了?

标签: redirectasp.net-corecookies

解决方案


推荐阅读