ASP.Net核心。检测是否在启动时配置为 https?

ASP.Net Core. Detect if configured for https on startup?

我有一个 .net ASP Core 2.1 应用程序。该应用程序可以通过 HTTP 或 HTTPS 进行设置。在启动时,我需要将 options.Cookie.SameSite 设置为 SameSite.None 如果我们 运行ning https,或者 -1 如果 运行ning http.

是否可以告诉应用程序在启动时如何配置为 运行。我在想我可能只需要在 appsettings.json 中放置一个标志来标记这种行为,但这有点蹩脚。

public void ConfigureServices(IServiceCollection services)
        {
            
            services.AddSession(options =>
            {
                //if https I want below. If not I want it to be set to -1
                options.Cookie.SameSite = SameSiteMode.None;
                options.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest;
                options.Cookie.IsEssential = true;
            });

我觉得你可以在附加cookie的时候判断是http还是https。像下面这样。

public void ConfigureServices(IServiceCollection services)
    {
        services.AddSession(options =>
        {
            options.Cookie.SameSite = SameSiteMode.None;
            options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
            options.Cookie.IsEssential = true;
        });
        services.Configure<CookiePolicyOptions>(options =>
        {
            options.CheckConsentNeeded = context => true;
            options.MinimumSameSitePolicy = SameSiteMode.None;
            options.OnAppendCookie = cookieContext =>
                CheckSameSite(cookieContext.Context, cookieContext.CookieOptions);
        });
    }
private void CheckSameSite(HttpContext httpContext, CookieOptions options)
    {
        if (options.SameSite == SameSiteMode.None)
        {      
            if (!(httpContext.Request.IsHttps))
            {
                options.SameSite = (SameSiteMode)(-1);
            }
        }
    }
//....
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
      //...
      app.UseCookiePolicy();
      //...
    }

测试结果(记得先清除cookie):