AspNetCore3.1_Middleware源码解析_3_HttpsRedirection
概述
上文提到3.1版本默认没有使用Hsts,但是使用了这个中间件。看名字就很好理解,https跳转,顾名思义,就是跳转到
https地址。
使用场景,当用户使用http访问网站时,自动跳转到https地址。这样更加安全,不需要用户特意输入https://协议。
具体做了些我们一起来看看。
app.UseHttpsRedirection();
使用方法
跟Hsts一样,HttpsRedirection默认是不需要注入的,除非你需要修改默认配置。
services.AddHttpsRedirection(config =>
{
//https地址的端口号,默认null
config.HttpsPort = 12345;
//跳转响应的状态码,默认307
config.RedirectStatusCode = 302;
});
直接使用中间件即可
app.UseHttpsRedirection();
源码解析
源代码很简单,只有两个类:HttpsRedirectionOptions配置类,HttpsRedirectionMiddleware中间件
HttpsRedirectionOptions就只有两个配置项
/// <summary>
/// Options for the HttpsRedirection middleware
/// </summary>
public class HttpsRedirectionOptions
{
/// <summary>
/// The status code used for the redirect response. The default is 307.
/// </summary>
public int RedirectStatusCode { get; set; } = StatusCodes.Status307TemporaryRedirect;
/// <summary>
/// The HTTPS port to be added to the redirected URL.
/// </summary>
/// <remarks>
/// If the HttpsPort is not set, we will try to get the HttpsPort from the following:
/// 1. HTTPS_PORT environment variable
/// 2. IServerAddressesFeature
/// If that fails then the middleware will log a warning and turn off.
/// </remarks>
public int? HttpsPort { get; set; }
}
重点看下中间件做了些什么。代码量很少,大体是这些逻辑。
- 如果请求是Https,跳过本中间件
- 中间件会依次尝试从这三个地方取端口号:HttpsRedirectionOptions的配置,HttpsRedirectionOptions,HTTPS_PORT环境变量或配置,IServerAddressesFeature(如果Webhost上绑定了https地址,本中间件能够解析出来端口号)。
- 如果没有解析出来https的端口号,则跳过本中间件。
- 如果能够解析出来https端口号,则拼接出来https地址,返回307跳转响应报文(或者配置的其他状态码)。
注:3.1同时支持HTTPS_PORT和ANCM_HTTPS_PORT这两个环境变量。

https://docs.microsoft.com/en-us/dotnet/core/compatibility/2.2-3.0
public class HttpsRedirectionMiddleware
{
private const int PortNotFound = -1;
private readonly RequestDelegate _next;
private readonly Lazy<int> _httpsPort;
private readonly int _statusCode;
private readonly IServerAddressesFeature _serverAddressesFeature;
private readonly IConfiguration _config;
private readonly ILogger _logger;
/// <summary>
/// Initializes the HttpsRedirectionMiddleware
/// </summary>
/// <param name="next"></param>
/// <param name="options"></param>
/// <param name="config"></param>
/// <param name="loggerFactory"></param>
public HttpsRedirectionMiddleware(RequestDelegate next, IOptions<HttpsRedirectionOptions> options, IConfiguration config, ILoggerFactory loggerFactory)
{
_next = next ?? throw new ArgumentNullException(nameof(next));
_config = config ?? throw new ArgumentNullException(nameof(config));
if (options == null)
{
throw new ArgumentNullException(nameof(options));
}
var httpsRedirectionOptions = options.Value;
if (httpsRedirectionOptions.HttpsPort.HasValue)
{
_httpsPort = new Lazy<int>(() => httpsRedirectionOptions.HttpsPort.Value);
}
else
{
_httpsPort = new Lazy<int>(TryGetHttpsPort);
}
_statusCode = httpsRedirectionOptions.RedirectStatusCode;
_logger = loggerFactory.CreateLogger<HttpsRedirectionMiddleware>();
}
/// <summary>
/// Initializes the HttpsRedirectionMiddleware
/// </summary>
/// <param name="next"></param>
/// <param name="options"></param>
/// <param name="config"></param>
/// <param name="loggerFactory"></param>
/// <param name="serverAddressesFeature">The</param>
public HttpsRedirectionMiddleware(RequestDelegate next, IOptions<HttpsRedirectionOptions> options, IConfiguration config, ILoggerFactory loggerFactory,
IServerAddressesFeature serverAddressesFeature)
: this(next, options, config, loggerFactory)
{
_serverAddressesFeature = serverAddressesFeature ?? throw new ArgumentNullException(nameof(serverAddressesFeature));
}
/// <summary>
/// Invokes the HttpsRedirectionMiddleware
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public Task Invoke(HttpContext context)
{
if (context.Request.IsHttps)
{
return _next(context);
}
var port = _httpsPort.Value;
if (port == PortNotFound)
{
return _next(context);
}
var host = context.Request.Host;
if (port != 443)
{
host = new HostString(host.Host, port);
}
else
{
host = new HostString(host.Host);
}
var request = context.Request;
var redirectUrl = UriHelper.BuildAbsolute(
"https",
host,
request.PathBase,
request.Path,
request.QueryString);
context.Response.StatusCode = _statusCode;
context.Response.Headers[HeaderNames.Location] = redirectUrl;
_logger.RedirectingToHttps(redirectUrl);
return Task.CompletedTask;
}
// Returns PortNotFound (-1) if we were unable to determine the port.
private int TryGetHttpsPort()
{
// The IServerAddressesFeature will not be ready until the middleware is Invoked,
// Order for finding the HTTPS port:
// 1. Set in the HttpsRedirectionOptions
// 2. HTTPS_PORT environment variable
// 3. IServerAddressesFeature
// 4. Fail if not sets
var nullablePort = _config.GetValue<int?>("HTTPS_PORT") ?? _config.GetValue<int?>("ANCM_HTTPS_PORT");
if (nullablePort.HasValue)
{
var port = nullablePort.Value;
_logger.PortLoadedFromConfig(port);
return port;
}
if (_serverAddressesFeature == null)
{
_logger.FailedToDeterminePort();
return PortNotFound;
}
foreach (var address in _serverAddressesFeature.Addresses)
{
var bindingAddress = BindingAddress.Parse(address);
if (bindingAddress.Scheme.Equals("https", StringComparison.OrdinalIgnoreCase))
{
// If we find multiple different https ports specified, throw
if (nullablePort.HasValue && nullablePort != bindingAddress.Port)
{
_logger.FailedMultiplePorts();
return PortNotFound;
}
else
{
nullablePort = bindingAddress.Port;
}
}
}
if (nullablePort.HasValue)
{
var port = nullablePort.Value;
_logger.PortFromServer(port);
return port;
}
_logger.FailedToDeterminePort();
return PortNotFound;
}
}
OK,完成了。
AspNetCore3.1_Middleware源码解析_3_HttpsRedirection的更多相关文章
- AspNetCore3.1_Secutiry源码解析_4_Authentication_JwtBear
title: "AspNetCore3.1_Secutiry源码解析_4_Authentication_JwtBear" date: 2020-03-22T16:29:29+08: ...
- AspNetCore3.1_Secutiry源码解析_1_目录
文章目录 AspNetCore3.1_Secutiry源码解析_1_目录 AspNetCore3.1_Secutiry源码解析_2_Authentication_核心项目 AspNetCore3.1_ ...
- AspNetCore3.1_Secutiry源码解析_2_Authentication_核心对象
系列文章目录 AspNetCore3.1_Secutiry源码解析_1_目录 AspNetCore3.1_Secutiry源码解析_2_Authentication_核心项目 AspNetCore3. ...
- AspNetCore3.1_Secutiry源码解析_3_Authentication_Cookies
系列文章目录 AspNetCore3.1_Secutiry源码解析_1_目录 AspNetCore3.1_Secutiry源码解析_2_Authentication_核心流程 AspNetCore3. ...
- AspNetCore3.1_Secutiry源码解析_5_Authentication_OAuth
title: "AspNetCore3.1_Secutiry源码解析_5_Authentication_OAuth" date: 2020-03-24T23:27:45+08:00 ...
- AspNetCore3.1_Secutiry源码解析_6_Authentication_OpenIdConnect
title: "AspNetCore3.1_Secutiry源码解析_6_Authentication_OpenIdConnect" date: 2020-03-25T21:33: ...
- AspNetCore3.1_Secutiry源码解析_8_Authorization_授权框架
目录 AspNetCore3.1_Secutiry源码解析_1_目录 AspNetCore3.1_Secutiry源码解析_2_Authentication_核心流程 AspNetCore3.1_Se ...
- AspNetCore3.1源码解析_2_Hsts中间件
title: "AspNetCore3.1源码解析_2_Hsts中间件" date: 2020-03-16T12:40:46+08:00 draft: false --- 概述 在 ...
- 【原】Android热更新开源项目Tinker源码解析系列之三:so热更新
本系列将从以下三个方面对Tinker进行源码解析: Android热更新开源项目Tinker源码解析系列之一:Dex热更新 Android热更新开源项目Tinker源码解析系列之二:资源文件热更新 A ...
随机推荐
- 3dmax2012卸载/安装失败/如何彻底卸载清除干净3dmax2012注册表和文件的方法
3dmax2012提示安装未完成,某些产品无法安装该怎样解决呢?一些朋友在win7或者win10系统下安装3dmax2012失败提示3dmax2012安装未完成,某些产品无法安装,也有时候想重新安装3 ...
- Alfresco的安装配置(Centos6系统中安装)
Alfresco是一款开源的企业内容管理系统(ECMS),为企业提供了日常的文档管理.协同工作.工作记录管理.知识管理.网络内容管理.图片管理等多种功能. Alfresco是目前应用最广泛的开源企业知 ...
- win10安装MAYA失败,怎么强力卸载删除注册表并重新安装
一些搞设计的朋友在win10系统下安装MAYA失败或提示已安装,也有时候想重新安装MAYA的时候会出现本电脑windows系统已安装MAYA,你要是不留意直接安装MAYA,只会安装MAYA的附件或者直 ...
- cas单点登录打包时下载慢!
环境:win10 百度网盘下载 版本: cas-overlay-template-5.3 提取码 d1b6 添加阿里的到pom.xml 注意添加到第一列 <!--阿里云仓库--& ...
- SVN图标含义说明
最经都在用Svn,对他上面的很多状态图标不是很理解,看了看它的帮助文档,说的很清楚,特地截张图. Svn不同状态图标及说明 - 简单 - 简单 Normal A fresh checked ...
- myecplise上将工程部署到应用下时,经常出现 An internal error occurred during: "Add Deployment". java.lang.NullPointEx
myecplise上将工程部署到应用下时,经常出现 An internal error occurred during: "Add Deployment". java.lang.N ...
- 微软推出中文学习AI助手Microsoft Learn Chinese
编者按:美国总统特朗普访华期间,他6岁的外孙女阿拉贝拉用中文普通话演唱和背诵传统诗歌的视频在中国社交媒体上引起广泛关注,可以感受得到,越来越多的人对中文学习充满了兴趣.智能私教微软小英帮助很多中国 ...
- Zookeeper的使用场景和集群配置
Zookeeper的介绍 ZK在分布式系统的应用 Zookeeper搭建 集群角色介绍 ZK的常用命令 一.Zookeeper的介绍 官方:ZooKeeper是一个分布式的,开放源码的分布式应用程序协 ...
- idea通过maven打jar包不成功或无法加载主类或打成功也找不到jar包
这个问题纠结了我一天,在网上也搜了一些方法,现在把我自己的处理过程记录一下,以方便遇到此类问题的小伙伴参考: 第一步:查看idea的jdk版本与Windows安装的jdk是不是同一个版本,如下图 第二 ...
- Dubbo源码解析之SPI(一):扩展类的加载过程
Dubbo是一款开源的.高性能且轻量级的Java RPC框架,它提供了三大核心能力:面向接口的远程方法调用.智能容错和负载均衡,以及服务自动注册和发现. Dubbo最早是阿里公司内部的RPC框架,于 ...