You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Windows服务器特定SSL端口部署Asp.net Core 6 Web API

解决Asp.net Core 6 Kestrel托管找不到SSL证书的问题

直接通过app.run("https://api.xxxxxx.com:10001")启动时,Kestrel无法自动识别你在IIS或证书管理器中绑定的证书,需要单独为Kestrel配置证书关联方式,以下是几种可行方案:

方案1:通过配置文件指定证书(推荐)

修改项目根目录的appsettings.json,添加Kestrel的HTTPS端点配置,让Kestrel自动从证书存储中查找匹配证书:

{
  "Kestrel": {
    "Endpoints": {
      "Https": {
        "Url": "https://api.xxxxxx.com:10001",
        "Certificate": {
          "Subject": "api.xxxxxx.com",
          "Store": "My",
          "Location": "LocalMachine"
        }
      }
    }
  }
}

之后将Program.cs中的app.Run("https://xxx")改为默认的app.Run()即可,Kestrel会自动读取配置文件中的设置。

方案2:在代码中手动配置证书查找逻辑

如果不想修改配置文件,可直接在Program.cs中编写证书查找逻辑:

using System.Security.Cryptography.X509Certificates;

var builder = WebApplication.CreateBuilder(args);

// 配置Kestrel监听HTTPS端口并关联证书
builder.WebHost.ConfigureKestrel(serverOptions =>
{
    serverOptions.ListenAnyIP(10001, listenOptions =>
    {
        listenOptions.UseHttps(httpsOptions =>
        {
            httpsOptions.ServerCertificateSelector = (context, name) =>
            {
                using var certStore = new X509Store(StoreName.My, StoreLocation.LocalMachine);
                certStore.Open(OpenFlags.ReadOnly);
                // 根据证书主题名称查找
                var matchedCerts = certStore.Certificates.Find(X509FindType.FindBySubjectName, "api.xxxxxx.com", validOnly: false);
                return matchedCerts.Count > 0 ? matchedCerts[0] : null;
            };
        });
    });
});

var app = builder.Build();

// 中间件配置...

app.Run();

方案3:通过证书指纹精准定位

如果存在多个同名证书,使用证书指纹能更精准匹配:

using System.Security.Cryptography.X509Certificates;

var builder = WebApplication.CreateBuilder(args);

builder.WebHost.ConfigureKestrel(serverOptions =>
{
    serverOptions.ListenAnyIP(10001, listenOptions =>
    {
        // 替换为你的证书指纹(需去掉指纹中的空格)
        var certThumbprint = "AB12CD34EF56GH78IJ90KL12MN34OP56QR78ST90";
        using var certStore = new X509Store(StoreName.My, StoreLocation.LocalMachine);
        certStore.Open(OpenFlags.ReadOnly);
        var matchedCerts = certStore.Certificates.Find(X509FindType.FindByThumbprint, certThumbprint, validOnly: false);
        
        if (matchedCerts.Count > 0)
        {
            listenOptions.UseHttps(matchedCerts[0]);
        }
        else
        {
            throw new InvalidOperationException("未找到指定指纹的SSL证书");
        }
    });
});

var app = builder.Build();

// 中间件配置...

app.Run();

证书指纹获取方式:打开证书管理器→找到目标证书→右键属性→详细信息→复制指纹后手动删除所有空格

关键注意事项

  • 权限检查:运行EXE的用户需具备读取证书存储的权限,可右键证书→所有任务→管理私钥→添加运行用户并授予读取权限,或直接以管理员身份启动EXE。
  • 存储位置匹配:如果证书导入的是当前用户的个人存储,需将代码或配置中的StoreLocation改为CurrentUser。
  • 独立托管逻辑:IIS的端口绑定与Kestrel托管无关,Kestrel作为独立服务器需要单独配置证书关联,不能依赖IIS的绑定设置。

内容的提问来源于stack exchange,提问作者Rajesh Dua

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 02:05:30