代码之家  ›  专栏  ›  技术社区  ›  VSDekar

配置ASP。用于HTTPS的NET Core 2.0 Kestrel

  •  25
  • VSDekar  · 技术社区  · 7 年前

    TL;DR现在使用ASP设置HTTPS的正确方法是什么。NET Core 2.0?

    我想将我的项目配置为使用https和证书,如图所示 BUILD 2017 appsettings.json hosting.json ,通过代码,和 launchsettings.json 我们还可以设置URL和端口。

    有“标准”的方法吗?

    这是我的 appsettings.development.json

    {
      "Kestrel": {
        "Endpoints": {
          "Localhost": {
            "Address": "127.0.0.1",
            "Port": "40000"
          },
          "LocalhostWithHttps": {
            "Address": "127.0.0.1",
            "Port": "40001",
            "Certificate": {
              "HTTPS": {
                "Source": "Store",
                "StoreLocation": "LocalMachine",
                "StoreName": "My",
                "Subject": "CN=localhost",
                "AllowInvalid": true
              }
            }
          }
        }
      }
    }
    

    启动设置。json dotnet run

    这是我的 Program.cs Startup.cs

    public class Program
    {
        public static void Main(string[] args)
        {
            BuildWebHost(args).Run();
        }
    
        public static IWebHost BuildWebHost(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>()
                .Build();
    }
    
    public class Startup
    {
        public IConfiguration Configuration { get; }
        public string Authority { get; set; } = "Authority";
        public string ClientId { get; set; } = "ClientId";
    
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }
    
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<MvcOptions>(options => options.Filters.Add(new RequireHttpsAttribute()));
    
            JsonConvert.DefaultSettings = () => new JsonSerializerSettings() {
                NullValueHandling = NullValueHandling.Ignore
            };
    
            services.AddSingleton<IRepository, AzureSqlRepository>(x => new AzureSqlRepository(Configuration.GetConnectionString("DefaultConnection")));
            services.AddSingleton<ISearchSplitService, SearchSplitService>();
    
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddJwtBearer(options => new JwtBearerOptions {
                    Authority = this.Authority,
                    Audience = this.ClientId
            });
    
            services.AddMvc();
        }
    
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions() { HotModuleReplacement = true, ReactHotModuleReplacement = true, HotModuleReplacementEndpoint = "/dist/__webpack_hmr" });
            }
    
            app.UseStaticFiles();
            app.UseAuthentication();
    
            app.UseMvc(routes => {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{id?}");
    
                routes.MapSpaFallbackRoute(
                    name: "spa-fallback",
                    defaults: new { controller = "Home", action = "Index" });
            });
        }
    }
    

    正如我所说,我无法使它在任何情况下工作。现在使用ASP设置HTTPS的正确方法是什么。NET Core 2.0?

    1 回复  |  直到 7 年前
        1
  •  36
  •   Shimmy Weitzhandler 500 - Internal Server Error    5 年前

    不幸的是,基于配置的方式设置HTTPS的方式在ASP启动之前已在各种视频或教程中显示。NET Core 2.0没有进入最终版本。

    in this announcement ,并使用 ListenOptions.UseHttps

    var host = new WebHostBuilder()
        .UseKestrel(options =>
        {
            options.ListenAnyIP(443, listenOptions => 
            {
                listenOptions.UseHttps("server.pfx", "password");
            });
        })
        .UseStartup<Startup>()
        .Build();
    

    而且 This has been fixed since.

    Tratcher on GitHub :

    "Kestrel": {
      "Endpoints": {
        "HTTPS": {
          "Url": "https://*:443",
          "Certificate": {
            "Path": "server.pfx",
            "Password": "password"
          }
        }
      }
    }
    

    ,您需要首先从证书存储中手动检索证书。

    .UseKestrel(options =>
    {
        // listen for HTTP
        options.ListenLocalhost(40000);
    
        // retrieve certificate from store
        using (var store = new X509Store(StoreName.My))
        {
            store.Open(OpenFlags.ReadOnly);
            var certs = store.Certificates.Find(X509FindType.FindBySubjectName, 
                "localhost", false);
            if (certs.Count > 0)
            {
                var certificate = certs[0];
    
                // listen for HTTPS
                options.ListenLocalhost(40001, listenOptions =>
                {
                    listenOptions.UseHttps(certificate);
                });
            }
        }
    })