Host filtering with ASP.NET Core Kestrel web server
Note
This isn't the latest version of this article. For the current release, see the .NET 8 version of this article.
Warning
This version of ASP.NET Core is no longer supported. For more information, see .NET and .NET Core Support Policy. For the current release, see the .NET 8 version of this article.
Important
This information relates to a pre-release product that may be substantially modified before it's commercially released. Microsoft makes no warranties, express or implied, with respect to the information provided here.
For the current release, see the .NET 8 version of this article.
While Kestrel supports configuration based on prefixes such as http://example.com:5000
, Kestrel largely ignores the host name. Host localhost
is a special case used for binding to loopback addresses. Any host other than an explicit IP address binds to all public IP addresses. Host
headers aren't validated.
As a workaround, use Host Filtering Middleware. The middleware is added by CreateDefaultBuilder, which calls AddHostFiltering:
public class Program
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>();
}
Host Filtering Middleware is disabled by default. To enable the middleware, define an AllowedHosts
key in appsettings.json
/appsettings.{Environment}.json
. The value is a semicolon-delimited list of host names without port numbers:
appsettings.json
:
{
"AllowedHosts": "example.com;localhost"
}
Note
Forwarded Headers Middleware also has an AllowedHosts option. Forwarded Headers Middleware and Host Filtering Middleware have similar functionality for different scenarios. Setting AllowedHosts
with Forwarded Headers Middleware is appropriate when the Host
header isn't preserved while forwarding requests with a reverse proxy server or load balancer. Setting AllowedHosts
with Host Filtering Middleware is appropriate when Kestrel is used as a public-facing edge server or when the Host
header is directly forwarded.
For more information on Forwarded Headers Middleware, see Configure ASP.NET Core to work with proxy servers and load balancers.
ASP.NET Core
Phản hồi
https://aka.ms/ContentUserFeedback.
Sắp ra mắt: Trong năm 2024, chúng tôi sẽ dần gỡ bỏ Sự cố với GitHub dưới dạng cơ chế phản hồi cho nội dung và thay thế bằng hệ thống phản hồi mới. Để biết thêm thông tin, hãy xem:Gửi và xem ý kiến phản hồi dành cho