asp.net core web项目在开发时根据launchsettings.json中的配置确定绑定的端口和ip地址,在生产环境,缺省端口号是5000和5001,如果想改变,需要使用UseUrls,在Program.cs中增加相应的代码:
internal static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration(build =>
{
build.AddJsonFile("appsettings.secrets.json", optional: true);
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>()
.UseUrls("http://0.0.0.0:5000");
})
.UseAutofac()
.UseSerilog();
}
如果希望使用配置文件设置,需要编写一点额外的代码,从配置文件或者命令行参数中获取需要绑定的地址。扩展的代码如下:
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using System;
namespace ZL.ServerUrlsExt
{
public static class CustomServerUrls
{
public static IWebHostBuilder UserConfigUrls(this IWebHostBuilder builder, string[] args)
{
//增加命令行配置
var configuration = new ConfigurationBuilder()
.AddCommandLine(args)
.AddJsonFile("appsettings.json", optional: true)
.Build();
//
var server = !string.IsNullOrEmpty(configuration["server.urls"]) ? configuration["server.urls"] : "http://0.0.0.0:5000;https://0.0.0.0:5001";
#if DEBUG
Console.WriteLine(server);
#endif
return builder.UseUrls(server);
}
}
}
使用时将UseUrls改为UseConfigUrls,传入参数改为从命令行接收的参数args:
internal static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration(build =>
{
build.AddJsonFile("appsettings.secrets.json", optional: true);
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>()
.UserConfigUrls(args);
})
.UseAutofac()
.UseSerilog();
}