当在主入口点使用WebHostBuilder时,我如何指定它绑定到的端口?
默认情况下,它使用5000。
请注意,这个问题是特定于新的ASP。NET Core API(目前在1.0.0-RC2中)。
当在主入口点使用WebHostBuilder时,我如何指定它绑定到的端口?
默认情况下,它使用5000。
请注意,这个问题是特定于新的ASP。NET Core API(目前在1.0.0-RC2中)。
当前回答
在。net Core 3.1上,只需遵循微软的文档,它非常简单:kestrel-aspnetcore-3.1
总结:
Add the below ConfigureServices section to CreateDefaultBuilder on Program.cs: // using Microsoft.Extensions.DependencyInjection; public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureServices((context, services) => { services.Configure<KestrelServerOptions>( context.Configuration.GetSection("Kestrel")); }) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); Add the below basic config to appsettings.json file (more config options on Microsoft article): "Kestrel": { "EndPoints": { "Http": { "Url": "http://0.0.0.0:5002" } } } Open CMD or Console on your project Publish/Debug/Release binaries folder and run: dotnet YourProject.dll Enjoy exploring your site/api at your http://localhost:5002
其他回答
或者,你也可以通过命令行运行app来指定端口。
简单地运行命令:
dotnet run --server.urls http://localhost:5001
注意:其中5001是要运行的端口。
在。net Core 3.1上,只需遵循微软的文档,它非常简单:kestrel-aspnetcore-3.1
总结:
Add the below ConfigureServices section to CreateDefaultBuilder on Program.cs: // using Microsoft.Extensions.DependencyInjection; public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureServices((context, services) => { services.Configure<KestrelServerOptions>( context.Configuration.GetSection("Kestrel")); }) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); Add the below basic config to appsettings.json file (more config options on Microsoft article): "Kestrel": { "EndPoints": { "Http": { "Url": "http://0.0.0.0:5002" } } } Open CMD or Console on your project Publish/Debug/Release binaries folder and run: dotnet YourProject.dll Enjoy exploring your site/api at your http://localhost:5002
当托管在docker容器(linux版本的我),你可能会得到一个'连接拒绝'消息。在这种情况下,您可以使用IP地址0.0.0.0,这意味着“这台机器上的所有IP地址”,而不是localhost环回来修复端口转发。
public class Program
{
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.UseUrls("http://0.0.0.0:5000/")
.Build();
host.Run();
}
}
另一种解决方案是使用主机。Json在项目的根目录中。
{
"urls": "http://localhost:60000"
}
然后在program。cs中
public static void Main(string[] args)
{
var config = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("hosting.json", true)
.Build();
var host = new WebHostBuilder()
.UseKestrel(options => options.AddServerHeader = false)
.UseConfiguration(config)
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.Build();
host.Run();
}
如果使用dotnet运行
dotnet run --urls="http://localhost:5001"