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