首页 技术 正文
技术 2022年11月9日
0 收藏 668 点赞 4,782 浏览 2605 个字

前言

在ASP.Net Core2.X调用的CreateWebHostBuilder和3.X的主要区别在于WebHost的调用,CreateDefaultBuilder被Host替换,另一个区别是对ConfigureWebHostDefaults()的调用;

由于新的主机生成器是通用主机生成器,因此我们也需要知道默认Web主机配置默认配置了什么.ConfigureWebHostDefaults为我们默认做了哪些配置?我们一起来看看他为我们默认配置的HostFiltering,HostFilteringMiddleware,其实他做的是对请求主机头的限制,也相当于一个请求主机头白名单,标识着某些主机头你可以访问,其余的你别访问了我这边未允许.

如何使用

在这之初打算的是为给大家分享一下如何配置;算了,我们一起开拓一下思维看看他是如何做的这个中间件吧.顺便再说说当我们使用ASP.NET Core在我们使用中如何配置,使用主机头白名单


services.PostConfigure<HostFilteringOptions>(options =>
{
if (options.AllowedHosts == null || options.AllowedHosts.Count == 0)
{
// "AllowedHosts": "localhost;127.0.0.1;[::1]"
var hosts = Configuration["AllowedHosts"]?.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
// Fall back to "*" to disable.
options.AllowedHosts = (hosts?.Length > 0 ? hosts : new[] { "*" });
}
});

HostFilteringOptions

  • AllowedHosts允许访问的Host主机
  • AllowEmptyHosts是否允许请求头Host的值为空访问 默认为true
  • IncludeFailureMessage 返回错误信息,默认为true

在Configure方法中添加HostFiltering中间件

   public void Configure(Microsoft.AspNetCore.Builder.IApplicationBuilder app, IWebHostEnvironment env)        {
app.UseHostFiltering();
app.Run(context =>
{
return context.Response.WriteAsync("Hello World! " + context.Request.Host);
});
}

appsettings.json

{
"AllowedHosts": "127.0.0.1"
}

这样就好了,那么我们再来测试一下看看.

源码解析

        /// <summary>
/// Processes requests
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public Task Invoke(HttpContext context)
{
var allowedHosts = EnsureConfigured();//获取允许Host集合 if (!CheckHost(context, allowedHosts))//判断当前Host是否在允许的Host集合中
{
return HostValidationFailed(context);//如果不在400
} return _next(context);//继续走下一个中间件
} private Task HostValidationFailed(HttpContext context)
{
context.Response.StatusCode = 400;
if (_options.IncludeFailureMessage)
{
context.Response.ContentLength = DefaultResponse.Length;
context.Response.ContentType = "text/html";
return context.Response.Body.WriteAsync(DefaultResponse, 0, DefaultResponse.Length);
}
return Task.CompletedTask;
}
private IList<StringSegment> EnsureConfigured()
{
if (_allowAnyNonEmptyHost == true || _allowedHosts?.Count > 0)//判断配置是否为空
{
return _allowedHosts;
} return Configure();
} private IList<StringSegment> Configure()
{
var allowedHosts = new List<StringSegment>();
if (_options.AllowedHosts?.Count > 0 && !TryProcessHosts(_options.AllowedHosts, allowedHosts))
{
_logger.WildcardDetected();
_allowedHosts = allowedHosts;
_allowAnyNonEmptyHost = true;
return _allowedHosts;
} if (allowedHosts.Count == 0)//至少一个Host
{
throw new InvalidOperationException("No allowed hosts were configured.");
} if (_logger.IsEnabled(LogLevel.Debug))
{
_logger.AllowedHosts(string.Join("; ", allowedHosts));
} _allowedHosts = allowedHosts;
return _allowedHosts;
}

总结

这篇文章主要也许能给大家开阔一下思维,其实他的实现逻辑很简单,当我们请求带着Host头去访问的时候,通过该中间件判断该Host头是否在我们预先配置好的里面,如果在里面那么就继续请求下一个中间件,如果说不在那么不好意思400

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,492
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,907
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,740
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,495
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,132
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,295