ASP.NET Core 启动地址配置方法及优先级顺序

前言

默认情况下,ASP.NET Core 使用下列 2 个启动地址:

1
2
http://localhost:5000
https://localhost:5001

同时,我们也可以通过配置或代码方式修改启动地址。

那么,这几种修改方式都是什么?谁最后起作用呢?

设置方法

1. applicationUrl 属性

launchSettings.json 文件中的 applicationUrl 属性,但是仅在本地开发计算机上使用:

1
2
3
4
5
6
"profiles": {
    "WebApplication1": {
        ...
        "applicationUrl": "http://localhost:5100",
    }
}

2.环境变量

环境变量 ASPNETCORE_URLS,有多个设置位置,下面演示的是使用 launchSettings.json 文件:

1
2
3
4
5
6
7
8
"profiles": {
    "WebApplication1": {
        ...
        "environmentVariables": {
            "ASPNETCORE_URLS": "http://localhost:5200"
        }
    }
}

3.命令行参数

命令行参数 --urls,有多个设置位置,下面演示的是使用 launchSettings.json 文件:

1
2
3
4
5
6
"profiles": {
    "WebApplication1": {
        ...
        "commandLineArgs": "--urls http://localhost:5300",
    }
}

4.UseUrls 方法

修改 ConfigureWebHostDefaults 方法:

1
2
3
4
5
6
7
public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseStartup<Startup>();
            webBuilder.UseUrls("http://localhost:5400");
        });

5.UseKestrel 方法

修改 ConfigureWebHostDefaults 方法:

1
2
3
4
5
6
7
public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseStartup<Startup>();
            webBuilder.UseKestrel(options=> options.ListenLocalhost(5500, opts => opts.Protocols = HttpProtocols.Http1));
        });

优先级

通过将上述设置方式进行组合,发现优先级顺序如下:

  • UseKestrel 方法
  • 命令行参数 --urls
  • UseUrls 方法
  • 环境变量 ASPNETCORE_URLS
  • applicationUrl 属性
  • 默认值

0%