asp.net core如何自定义端口/修改默认端口

.net core运行的默认端口是5000,可是不少时候咱们须要自定义端口。有两种方式html

写在ProgramMain方法里面

添加 .UseUrls()

var host = new WebHostBuilder()
    .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory())
    //添加这一行
    .UseUrls("http://*:5001", "http://*:5002")
    .UseIISIntegration()
    .UseStartup<Startup>()
    .Build();

添加 .UseSetting()

var host = new WebHostBuilder()
    .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory())
    //添加这一行
    .UseSetting(WebHostDefaults.ServerUrlsKey, "http://*:5001;http://*5002")
    .UseIISIntegration()
    .UseStartup<Startup>()
    .Build();

小结

UseUrlsUseSetting设置端口的一个封装而已,源码linux

public static IWebHostBuilder UseUrls(this IWebHostBuilder hostBuilder, params string[] urls)
{
    if (urls == null)
    {
        throw new ArgumentNullException(nameof(urls));
    }

    return hostBuilder.UseSetting(WebHostDefaults.ServerUrlsKey, string.Join(ServerUrlsSeparator, urls));
}

写在配置文件中

  1. 在项目中新建一个.json文件,例如config/hosting.json.内容:
{
  "urls": "http://*:5003;http://*:5004"
}
  1. Main方法添加配置
// using Microsoft.Extensions.Configuration;
public static void Main(string[] args)
{
    var config = new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory())
        // 这里添加配置文件
        .AddJsonFile(Path.Combine("config", "hosting.json"), true)
        .Build();

    var host = new WebHostBuilder()
        .UseKestrel()
        // 添加配置
        .UseConfiguration(config)
        .UseContentRoot(Directory.GetCurrentDirectory())
        .UseIISIntegration()
        .UseStartup<Startup>()
        .Build();

    host.Run();
}
  1. 最后别忘了在project.json中添加输出配置:(像我就直接把整个config目录放进去了)
"publishOptions": {
  "include": [
    "wwwroot",
    "**/*.cshtml",
    "appsettings.json",
    "web.config",
    "config"
  ]
},

小结

其实这种方法最终也是变成UseSetting,用appsetting.json也能够作到,源码:web

public static IWebHostBuilder UseConfiguration(this IWebHostBuilder hostBuilder, IConfiguration configuration)
{
    foreach (var setting in configuration.AsEnumerable())
    {
        hostBuilder.UseSetting(setting.Key, setting.Value);
    }

    return hostBuilder;
}

用环境变量

  • 环境变量的名字ASPNETCORE_URLS(过期的名字是:ASPNETCORE_SERVER.URLS)
  • 设置临时环境变量
    • linux:export ASPNETCORE_URLS="http://*:5001"
    • windows:set ASPNETCORE_URLS="http://*:5001"
  • 设置完以后运行便可
    dotnet xxx.dll

小结

环境变量的方法为什么能实现?在WebHostBuilder的构造函数中存在着这么一句:json

_config = new ConfigurationBuilder()
                .AddEnvironmentVariables(prefix: "ASPNETCORE_")
                .Build();

总结

前两种方法都是会变成UseSetting,而UseSetting的实现也很简单windows

public IWebHostBuilder UseSetting(string key, string value)
{
    _config[key] = value;
    return this;
}

只是设置了个key,value。环境变量方法最后也是设置个key,value。
那么,那种方法比较好呢?我的认为环境变量方法好一点,灵活,不用在代码里面多写一句代码。app

注意: 在上面中设置端口的http://*:xxx中,*别改为localhost或者ip,由于这样要么外网访问不了要么内网访问不了,至关蛋疼,写*改变环境也不用改,多爽!函数

相关文章
相关标签/搜索