為ASP.NetCore程序啟用SSL


緊接着上一篇搭建連接MySql的三層架構的ASP.NetCore2.0的WebApi的案例,這篇來實現為ASP.NetCore啟用SSL支持

由於ASP.NetCore默認服務器Kestrel不像iis Express那樣會自動生成本地證書,所以就需要手動構建pfx證書.

生成pfx證書

開發環境證書就用iis默認的本地證書即可,Cortana搜索:IIS,出現以下結果點擊

進入管理器:點擊服務器證書選項

選中以下本地默認證書后右鍵導出,指定路徑和密碼點擊確認.

修改Program中BuildWebHost以增加SSL支持

第一種方案:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using System.Net;

namespace ASP.Net_Core_API
{
    public class Program
    {
        public static void Main(string[] args)
        {
            BuildWebHost(args).Run();
        }

        public static IWebHost BuildWebHost(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>()
            .UseKestrel(options =>//設置Kestrel服務器
            {
                options.Listen(IPAddress.Loopback, 5001, listenOptions =>
                {           
            //填入之前iis中生成的pfx文件路徑和指定的密碼            
            listenOptions.UseHttps(
"D:\\DotNetCore\\ASP.Net Core API\\wwwroot\\dontCore.pfx", "111111");
        });

        })
       .Build();
    }
 }

此種方案無需更改其他代碼即可生效,點擊運行

可看到已監聽指定的端口5001,瀏覽器輸入https://127.0.0.1:5001/api/values,可看到已啟用ssl

第二種方案:同時支持http和https請求(基於appsettings.json配置)

由於上一種方案只支持https請求,但實際生產也需要http請求

實現核心代碼:

Program:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using System.Net;

namespace ASP.Net_Core_API
{
    public class Program
    {
        public static void Main(string[] args)
        {
            BuildWebHost(args).Run();
        }

        public static IWebHost BuildWebHost(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>()
            .UseKestrel(SetHost)//啟用Kestrel
            .Build();

        /// <summary>
        /// 配置Kestrel
        /// </summary>
        /// <param name="options"></param>
        private static void SetHost(Microsoft.AspNetCore.Server.Kestrel.Core.KestrelServerOptions options)
        {
            var configuration = (IConfiguration)options.ApplicationServices.GetService(typeof(IConfiguration));
            var host = configuration.GetSection("RafHost").Get<Host>();//依據Host類反序列化appsettings.json中指定節點
            foreach (var endpointKvp in host.Endpoints)
            {
                var endpointName = endpointKvp.Key;
                var endpoint = endpointKvp.Value;//獲取appsettings.json的相關配置信息
                if (!endpoint.IsEnabled)
                {
                    continue;
                }

                var address = IPAddress.Parse(endpoint.Address);
                options.Listen(address, endpoint.Port, opt =>
                {
                    if (endpoint.Certificate != null)//證書不為空使用UserHttps
                    {
                        switch (endpoint.Certificate.Source)
                        {
                            case "File":
                                opt.UseHttps(endpoint.Certificate.Path, endpoint.Certificate.Password);
                                break;
                            default:
                                throw new NotImplementedException($"文件 {endpoint.Certificate.Source}還沒有實現");
                        }

                        //opt.UseConnectionLogging();
                    }
                });

                options.UseSystemd();
            }
        }
    }

    /// <summary>
    /// 待反序列化節點
    /// </summary>
    public class Host
    {
        /// <summary>
        /// appsettings.json字典
        /// </summary>
        public Dictionary<string, Endpoint> Endpoints { get; set; }
    }

    /// <summary>
    /// 終結點
    /// </summary>
    public class Endpoint
    {
        /// <summary>
        /// 是否啟用
        /// </summary>
        public bool IsEnabled { get; set; }

        /// <summary>
        /// ip地址
        /// </summary>
        public string Address { get; set; }

        /// <summary>
        /// 端口號
        /// </summary>
        public int Port { get; set; }

        /// <summary>
        /// 證書
        /// </summary>
        public Certificate Certificate { get; set; }
    }

    /// <summary>
    /// 證書類
    /// </summary>
    public class Certificate
    {
        /// <summary>
        ////// </summary>
        public string Source { get; set; }

        /// <summary>
        /// 證書路徑()
        /// </summary>
        public string Path { get; set; }

        /// <summary>
        /// 證書密鑰
        /// </summary>
        public string Password { get; set; }
    }
}

appsettings.json

{
    "ConnectionStrings": {
        "MySqlConnection": "Server=localhost;database=NetCore_WebAPI-Mysql;uid=root;pwd=111111;"
    },
    "Logging": {
        "IncludeScopes": false,
        "Debug": {
            "LogLevel": {
                "Default": "Warning"
            }
        },
        "Console": {
            "LogLevel": {
                "Default": "Warning"
            }
        }
    },
  //以下為Kestrel配置信息,同時支持https和HTTP
"RafHost": { "Endpoints": { "Http": { "IsEnabled": true, "Address": "127.0.0.1", "Port": "5000" }, "Https": { "IsEnabled": true, "Address": "127.0.0.1", "Port": "5443", "Certificate": { "Source": "File", "Path": "wwwroot\\dontCore.pfx", "Password": "111111" } } } } }

點擊運行會發現控制台出現監聽兩個端口的提示,一個支持https一個支持http

 瀏覽器輸入http://127.0.0.1:5000/api/values 

http請求運行正常

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

 

https運行正常

專案下載鏈接:Demo

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM