找回密码
 会员注册
查看: 186|回复: 0

为ASP.NetCore程序启用SSL

[复制链接]

250

主题

1

回帖

819

积分

管理员

积分
819
发表于 2024-2-29 08:15:56 | 显示全部楼层 |阅读模式

由于ASP.NetCore默认服务器Kestrel不像iis Express那样会自动生成本地证书,所以就需要手动构建pfx证书.

生成pfx证书

开发环境证书就用iis默认的本地证书即可,Cortana搜索:IIS,出现以下结果点击

进入管理器:点击服务器证书选项

选中以下本地默认证书后右键导出,指定路径和密码点击确认.

修改Program中BuildWebHost以增加SSL支持

第一种方案:

复制代码
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Threading.Tasks;
  6. using Microsoft.AspNetCore;
  7. using Microsoft.AspNetCore.Hosting;
  8. using Microsoft.Extensions.Configuration;
  9. using Microsoft.Extensions.Logging;
  10. using System.Net;
  11. namespace ASP.Net_Core_API
  12. {
  13. public class Program
  14. {
  15. public static void Main(string[] args)
  16. {
  17. BuildWebHost(args).Run();
  18. }
  19. public static IWebHost BuildWebHost(string[] args) =>
  20. WebHost.CreateDefaultBuilder(args)
  21. .UseStartup<Startup>()
  22. .UseKestrel(options =>//设置Kestrel服务器
  23. {
  24. options.Listen(IPAddress.Loopback, 5001, listenOptions =>
  25. {           <br style="margin:0px; padding:0px" />            //填入之前iis中生成的pfx文件路径和指定的密码            <br style="margin:0px; padding:0px" />            listenOptions.UseHttps("D:\\DotNetCore\\ASP.Net Core API\\wwwroot\\dontCore.pfx", "111111"); <br style="margin:0px; padding:0px" />        }); <br style="margin:0px; padding:0px" />        })<br style="margin:0px; padding:0px" />       .Build();<br style="margin:0px; padding:0px" />    }<br style="margin:0px; padding:0px" /> }
复制代码
复制代码

此种方案无需更改其他代码即可生效,点击运行

可看到已监听指定的端口5001,浏览器输入https://127.0.0.1:5001/api/values,可看到已启用ssl

第二种方案:同时支持http和https请求(基于appsettings.json配置)

由于上一种方案只支持https请求,但实际生产也需要http请求

实现核心代码:

Program:

复制代码
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Threading.Tasks;
  6. using Microsoft.AspNetCore;
  7. using Microsoft.AspNetCore.Hosting;
  8. using Microsoft.Extensions.Configuration;
  9. using Microsoft.Extensions.Logging;
  10. using System.Net;
  11. namespace ASP.Net_Core_API
  12. {
  13. public class Program
  14. {
  15. public static void Main(string[] args)
  16. {
  17. BuildWebHost(args).Run();
  18. }
  19. public static IWebHost BuildWebHost(string[] args) =>
  20. WebHost.CreateDefaultBuilder(args)
  21. .UseStartup<Startup>()
  22. .UseKestrel(SetHost)//启用Kestrel
  23. .Build();
  24. /// <summary>
  25. /// 配置Kestrel
  26. /// </summary>
  27. /// <param name="options"></param>
  28. private static void SetHost(Microsoft.AspNetCore.Server.Kestrel.Core.KestrelServerOptions options)
  29. {
  30. var configuration = (IConfiguration)options.ApplicationServices.GetService(typeof(IConfiguration));
  31. var host = configuration.GetSection("RafHost").Get<Host>();//依据Host类反序列化appsettings.json中指定节点
  32. foreach (var endpointKvp in host.Endpoints)
  33. {
  34. var endpointName = endpointKvp.Key;
  35. var endpoint = endpointKvp.Value;//获取appsettings.json的相关配置信息
  36. if (!endpoint.IsEnabled)
  37. {
  38. continue;
  39. }
  40. var address = IPAddress.Parse(endpoint.Address);
  41. options.Listen(address, endpoint.Port, opt =>
  42. {
  43. if (endpoint.Certificate != null)//证书不为空使用UserHttps
  44. {
  45. switch (endpoint.Certificate.Source)
  46. {
  47. case "File":
  48. opt.UseHttps(endpoint.Certificate.Path, endpoint.Certificate.Password);
  49. break;
  50. default:
  51. throw new NotImplementedException($"文件 {endpoint.Certificate.Source}还没有实现");
  52. }
  53. //opt.UseConnectionLogging();
  54. }
  55. });
  56. options.UseSystemd();
  57. }
  58. }
  59. }
  60. /// <summary>
  61. /// 待反序列化节点
  62. /// </summary>
  63. public class Host
  64. {
  65. /// <summary>
  66. /// appsettings.json字典
  67. /// </summary>
  68. public Dictionary<string, Endpoint> Endpoints { get; set; }
  69. }
  70. /// <summary>
  71. /// 终结点
  72. /// </summary>
  73. public class Endpoint
  74. {
  75. /// <summary>
  76. /// 是否启用
  77. /// </summary>
  78. public bool IsEnabled { get; set; }
  79. /// <summary>
  80. /// ip地址
  81. /// </summary>
  82. public string Address { get; set; }
  83. /// <summary>
  84. /// 端口号
  85. /// </summary>
  86. public int Port { get; set; }
  87. /// <summary>
  88. /// 证书
  89. /// </summary>
  90. public Certificate Certificate { get; set; }
  91. }
  92. /// <summary>
  93. /// 证书类
  94. /// </summary>
  95. public class Certificate
  96. {
  97. /// <summary>
  98. /// 源
  99. /// </summary>
  100. public string Source { get; set; }
  101. /// <summary>
  102. /// 证书路径()
  103. /// </summary>
  104. public string Path { get; set; }
  105. /// <summary>
  106. /// 证书密钥
  107. /// </summary>
  108. public string Password { get; set; }
  109. }
  110. }
复制代码
复制代码

appsettings.json

复制代码
  1. {
  2. "ConnectionStrings": {
  3. "MySqlConnection": "Server=localhost;database=NetCore_WebAPI-Mysql;uid=root;pwd=111111;"
  4. },
  5. "Logging": {
  6. "IncludeScopes": false,
  7. "Debug": {
  8. "LogLevel": {
  9. "Default": "Warning"
  10. }
  11. },
  12. "Console": {
  13. "LogLevel": {
  14. "Default": "Warning"
  15. }
  16. }
  17. },<br style="margin:0px; padding:0px" />  //以下为Kestrel配置信息,同时支持https和HTTP
  18. "RafHost": {
  19. "Endpoints": {
  20. "Http": {
  21. "IsEnabled": true,
  22. "Address": "127.0.0.1",
  23. "Port": "5000"
  24. },
  25. "Https": {
  26. "IsEnabled": true,
  27. "Address": "127.0.0.1",
  28. "Port": "5443",
  29. "Certificate": {
  30. "Source": "File",
  31. "Path": "D:\\DotNetCore\\ASP.Net Core API\\wwwroot\\dontCore.pfx",
  32. "Password": "111111"
  33. }
  34. }
  35. }
  36. }
  37. }
复制代码
复制代码

点击运行会发现控制台出现监听两个端口的提示,一个支持https一个支持http

 

浏览器输入http://127.0.0.1:5000/api/values 

http请求运行正常

再输入https://127.0.0.1:5443/api/values

 

https运行正常


来源:https://blog.csdn.net/qq3401247010/article/details/78111488
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?会员注册

×
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 会员注册

本版积分规则

QQ|手机版|心飞设计-版权所有:微度网络信息技术服务中心 ( 鲁ICP备17032091号-12 )|网站地图

GMT+8, 2024-12-27 00:47 , Processed in 0.378366 second(s), 27 queries .

Powered by Discuz! X3.5

© 2001-2024 Discuz! Team.

快速回复 返回顶部 返回列表