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,由於這樣要麼外網訪問不了要麼內網訪問不了,至關蛋疼,寫*改變環境也不用改,多爽!函數

相關文章
相關標籤/搜索