AspNetCore3.1_Middleware源码解析_3_HttpsRedirection

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

AspNetCore3.1_Middleware源码解析_3_HttpsRedirection

holdengong   2020-03-16 我要评论
# 概述 上文提到3.1版本默认没有使用Hsts,但是使用了这个中间件。看名字就很好理解,https跳转,顾名思义,就是跳转到 https地址。 使用场景,当用户使用http访问网站时,自动跳转到https地址。这样更加安全,不需要用户特意输入https://协议。 具体做了些我们一起来看看。 ```csharp app.UseHttpsRedirection(); ``` # 使用方法 跟Hsts一样,HttpsRedirection默认是不需要注入的,除非你需要修改默认配置。 ```csharp services.AddHttpsRedirection(config => { //https地址的端口号,默认null config.HttpsPort = 12345; //跳转响应的状态码,默认307 config.RedirectStatusCode = 302; }); ``` 直接使用中间件即可 ```csharp app.UseHttpsRedirection(); ``` # 源码解析 源代码很简单,只有两个类:HttpsRedirectionOptions配置类,HttpsRedirectionMiddleware中间件 HttpsRedirectionOptions就只有两个配置项 ```csharp /// /// Options for the HttpsRedirection middleware /// public class HttpsRedirectionOptions { /// /// The status code used for the redirect response. The default is 307. /// public int RedirectStatusCode { get; set; } = StatusCodes.Status307TemporaryRedirect; /// /// The HTTPS port to be added to the redirected URL. /// /// public int? HttpsPort { get; set; } } ``` 重点看下中间件做了些什么。代码量很少,大体是这些逻辑。 - 如果请求是Https,跳过本中间件 - 中间件会依次尝试从这三个地方取端口号:HttpsRedirectionOptions的配置,HttpsRedirectionOptions,HTTPS_PORT环境变量或配置,IServerAddressesFeature(*如果Webhost上绑定了https地址,本中间件能够解析出来端口号*)。 - 如果没有解析出来https的端口号,则跳过本中间件。 - 如果能够解析出来https端口号,则拼接出来https地址,返回307跳转响应报文(或者配置的其他状态码)。 ***注:3.1同时支持HTTPS_PORT和ANCM_HTTPS_PORT这两个环境变量。*** ![image](https://fs.31huiyi.com/782a3141-0f34-4631-bf5b-196b09d1e9a6.png) > https:/https://img.qb5200.com/download-x/docs.microsoft.com/en-ushttps://img.qb5200.com/download-x/dotnet/core/compatibility/2.2-3.0 ```csharp public class HttpsRedirectionMiddleware { private const int PortNotFound = -1; private readonly RequestDelegate _next; private readonly Lazy

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们