.net core 配置https 证书

本文介绍了如何在appsettings.json文件中配置HTTPS证书,这种方法相比在代码中硬编码更加灵活。通过添加‘Kestrel’节点并设置‘Endpoints’->‘Https’的相关属性,包括URL、证书路径和密码,可以实现HTTPS服务的配置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

通过appsettings.json 配置HTTPS证书,这样配置比写在代码中更灵活。

在appsettings.json 添加如下代码块即可

"Kestrel": {
        "Endpoints": {
            "Https": {
                "Url": "https://*:443",
                "Certificate": {
                    "Path": "域名.com.pfx",
                    "Password": "证书的密码"
                }
            }
        }
    }

整体如下

{
    "Logging": {
        "LogLevel": {
            "Default": "Information",
            "Microsoft": "Warning",
            "Microsoft.Hosting.Lifetime": "Information"
        }
    },
    "AllowedHosts": "*",
    "Kestrel": {
        "Endpoints": {
            "Https": {
                "Url": "https://*:443",
                "Certificate": {
                    "Path": "域名.com.pfx",
                    "Password": "证书的密码"
                }
            }
        }
    }
}
.NET 9中,忽略HTTPS证书的验证通常不推荐在生产环境中使用,因为这会降低通信的安全性。然而,在开发或测试环境中,有时需要忽略HTTPS证书的验证。以下是如何在.NET 9中忽略HTTPS证书的方法: 1. **使用`HttpClientHandler`配置`ServerCertificateCustomValidationCallback`**: ```csharp using System; using System.Net.Http; public class HttpClientIgnoreCertificate { public static HttpClientHandler GetHttpClientHandler() { var handler = new HttpClientHandler { ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => true }; return handler; } public static void Main() { var handler = GetHttpClientHandler(); var client = new HttpClient(handler); var response = client.GetAsync("https://example.com").Result; Console.WriteLine(response.StatusCode); } } ``` 2. **使用`HttpClient`的构造函数传递自定义的`HttpClientHandler`**: ```csharp using System; using System.Net.Http; public class HttpClientIgnoreCertificate { public static void Main() { var handler = new HttpClientHandler { ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => true }; var client = new HttpClient(handler); var response = client.GetAsync("https://example.com").Result; Console.WriteLine(response.StatusCode); } } ``` 3. **在`Startup`类中配置(适用于ASP.NET Core应用)**: ```csharp using System.Net.Http; using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.DependencyInjection; public class Startup { public void ConfigureServices(IServiceCollection services) { services.AddHttpClient("ignore-ssl", c => { // 其他配置 }).ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => true }); } public void Configure(IApplicationBuilder app) { // 配置中间件 } } ``` 这些方法在开发或测试环境中非常有用,但在生产环境中应谨慎使用,以确保通信的安全性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值