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


.net core运行的默认端口是5000,但是很多时候我们需要自定义端口。有两种方式

写在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设置端口的一个封装而已,源码

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也可以做到,源码:

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的构造函数中存在着这么一句:

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

总结

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

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

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

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


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM