紧接着上一篇搭建连接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, , listenOptions =>
{           
            //填入之前iis中生成的pfx文件路径和指定的密码            
            listenOptions.UseHttps("D:\\DotNetCore\\ASP.Net Core API\\wwwroot\\dontCore.pfx", "");
        });
        })
       .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": ""
},
"Https": {
"IsEnabled": true,
"Address": "127.0.0.1",
"Port": "",
"Certificate": {
"Source": "File",
"Path": "wwwroot\\dontCore.pfx",
"Password": ""
}
}
}
}
}

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

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

http请求运行正常

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

https运行正常

专案下载链接:Demo

为ASP.NetCore程序启用SSL的更多相关文章

  1. .NET CORE学习笔记系列(4)——ASP.NET CORE 程序启用SSL

    一.什么是SSL? 1.概念: SSL(Secure Sockets Layer 安全套接层),及其继任者传输层安全(Transport Layer Security,TLS)是为网络通信提供安全及数 ...

  2. Asp.NetCore程序发布到CentOs(含安装部署netcore)--最佳实践(二)

    Asp.NetCore程序发布到CentOs(含安装部署netcore)--最佳实践(一) 接上一篇 3. Nginx配置反向代理 3.1 cnetos 安装nginx 首先,我们需要在服务器上安装N ...

  3. Asp.NetCore程序发布到CentOs(含安装部署netcore)--最佳实践(一)

    环境 本地 win7 服务器:Virtual Box 上的Centos ssh工具: Xshell 文件传输: xftp 1.在本地创建asp.net core应用发布 1.1 使用Vs2017 新建 ...

  4. 使用PowerShell自动部署ASP.NetCore程序到IIS

    Windows PowerShell 是一种命令行外壳程序和脚本环境,使命令行用户和脚本编写者可以利用 .NET Framework的强大功能.有关于更多PowerShell的信息,可参阅百度词条 接 ...

  5. Asp.NetCore程序发布到CentOs(含安装部署netcore)--最佳实践

    原文:Asp.NetCore程序发布到CentOs(含安装部署netcore)--最佳实践 环境 本地 win7 服务器:Virtual Box 上的Centos ssh工具: Xshell 文件传输 ...

  6. Dotnetcore或owin程序启用SSL的方法

    https端口需要绑定SSL证书 操作方法与步骤如下: 在IIS中创建证书 查看证书的指纹 使用命令行绑定端口与证书 上述第三步也可以更换为创建一个新的空网站,绑定https端口为相同端口并绑定证书, ...

  7. Asp.NetCore轻松学-部署到 IIS 进行托管

    前言 经过一段时间的学习,终于来到了部署服务这个环节,.NetCore 的部署方式非常的灵活多样,但是其万变不离其宗,所有的 Asp.NetCore 程序都基于端口的侦听,在部署的时候仅需要配置侦听地 ...

  8. 目录---Asp.NETCore轻松学系列【目录】

    随笔分类 - Asp.NETCore轻松学系列 Asp.NETCore轻松学系列阅读指引目录 摘要: 耗时两个多月,坚持写这个入门系列文章,就是想给后来者更好更快的上手体验,这个系列可以说是从入门到进 ...

  9. 【目录】Asp.NETCore轻松学系列

    随笔分类 - Asp.NETCore轻松学系列 Asp.NETCore轻松学系列阅读指引目录 摘要: 耗时两个多月,坚持写这个入门系列文章,就是想给后来者更好更快的上手体验,这个系列可以说是从入门到进 ...

随机推荐

  1. Android 读写文件

    Android 读写文件 Android使用一个非常类似与其他平台上的基于磁盘的文件系统. 这节课讲述如何利用File APIs在Android文件系统中读写文件. File 对象非常适合于流式顺序数 ...

  2. 四张图揭秘中国AI人才现状

    本文数据来源:领英<全球AI领域人才报告> 最近有非常多的同学看了之前我们的一些文章和直播之后,多对AI领域跃跃欲试,本文我们结合一份人才报告(我个人感觉这份报告还是比较靠谱的),为大家揭 ...

  3. Day2 - Linux发展史

    第1章 Linux发展史 1.1 什么是操作系统 操作系统是人与计算机硬件的一个中介. 1.2 操作系统组成 操作系统类似与鸡蛋 蛋壳--------->系统中各种各样的软件 蛋清------- ...

  4. chrome开发工具指南(十一)

    检查资源 使用 Application 面板的 Frames 窗格可以按框架组织资源. 您也可以在 Sources 面板中停用 Group by folder 选项,按框架查看资源. 要按网域和文件夹 ...

  5. 在tomcat7中启用HTTPS的详细配置

    详见:http://blog.yemou.net/article/query/info/tytfjhfascvhzxcyt385 最简单的方法,直接用java里的keytool工具生成一个keysto ...

  6. 循环checked表单 元素

    var poject_Array = "";            $('input[name="yearCardPoject"]:checked').each ...

  7. 个人作业1——四则运算题目生成程序(java代码,基于控制台)

    一.题目描述: 从<构建之法>第一章的 "程序" 例子出发,像阿超那样,花二十分钟写一个能自动生成小学四则运算题目的命令行 "软件",满足以下需求: ...

  8. 团队作业4——第一次项目冲刺(Alpha版本)4.22

    团队作业4--第一次项目冲刺(Alpha版本) Day one: 会议照片 由于团队中的组员今天不在学校,所以我们的站立会议提前一天展开. 项目进展 由于今天是Alpha版本项目冲刺的第一天,所以没有 ...

  9. 如何让eclipse在程序修改后,点击运行可以自动保存。

    preferences>run/debug>launching里面save required dirty editors before launching选always就自动保存咯选pro ...

  10. 201521123003《Java程序设计》第8周学习总结

    1. 本周学习总结 1.1 以你喜欢的方式(思维导图或其他)归纳总结集合与泛型相关内容. 2. 书面作业 本次作业题集集合 1.List中指定元素的删除(题目4-1) 1.1 实验总结 我们利用Sca ...