如何指定托管 ASP.NET Core 应用程序的端口?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37365277/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 09:47:38  来源:igfitidea点击:

How to specify the port an ASP.NET Core application is hosted on?

.netasp.net-core

提问by Drew Noakes

When using WebHostBuilderin a Mainentry-point, how can I specify the port it binds to?

当使用WebHostBuilder在一个Main入口点,我怎么可以指定它绑定到端口?

By default it uses 5000.

默认情况下,它使用 5000。

Note that this question is specific to the new ASP.NET Core API (currently in 1.0.0-RC2).

请注意,此问题特定于新的 ASP.NET Core API(目前在 1.0.0-RC2 中)。

回答by Kévin Chalet

In ASP.NET Core 3.1, there are 4 main ways to specify a custom port:

在 ASP.NET Core 3.1 中,有 4 种主要方式来指定自定义端口:

  • Using command line arguments, by starting your .NET application with --urls=[url]:
  • 使用命令行参数,通过使用以下命令启动您的 .NET 应用程序--urls=[url]
dotnet run --urls=http://localhost:5001/
  • Using appsettings.json, by adding a Urlsnode:
  • 使用appsettings.json, 通过添加Urls节点:
{
  "Urls": "http://localhost:5001"
}
  • Using environment variables, with ASPNETCORE_URLS=http://localhost:5001/.
  • Using UseUrls(), if you prefer doing it programmatically:
  • 使用环境变量,带有ASPNETCORE_URLS=http://localhost:5001/.
  • 使用UseUrls(), 如果您更喜欢以编程方式执行此操作:
public static class Program
{
    public static void Main(string[] args) =>
        CreateHostBuilder(args).Build().Run();

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(builder =>
            {
                builder.UseStartup<Startup>();
                builder.UseUrls("http://localhost:5001/");
            });
}

Or, if you're still using the web host builder instead of the generic host builder:

或者,如果您仍在使用网络主机构建器而不是通用主机构建器:

public class Program
{
    public static void Main(string[] args) =>
        new WebHostBuilder()
            .UseKestrel()
            .UseContentRoot(Directory.GetCurrentDirectory())
            .UseIISIntegration()
            .UseStartup<Startup>()
            .UseUrls("http://localhost:5001/")
            .Build()
            .Run();
}

回答by menxin

You can insert Kestrel section in asp.net core 2.1+ appsettings.json file.

您可以在 asp.net core 2.1+ appsettings.json 文件中插入 Kestrel 部分。

  "Kestrel": {
    "EndPoints": {
      "Http": {
        "Url": "http://0.0.0.0:5002"
      }
    }
  },

回答by Casey

Follow up answer to help anyone doing this with the VS docker integration. I needed to change to port 8080 to run using the "flexible" environment in google appengine.

跟进答案以帮助任何使用 VS docker 集成执行此操作的人。我需要更改为端口 8080 才能使用 google appengine 中的“灵活”环境运行。

You'll need the following in your Dockerfile:

您的 Dockerfile 中需要以下内容:

ENV ASPNETCORE_URLS=http://+:8080
EXPOSE 8080

and you'll need to modify the port in docker-compose.yml as well:

并且您还需要修改 docker-compose.yml 中的端口:

    ports:
      - "8080"

回答by Dennis

Alternative solution is to use a hosting.jsonin the root of the project.

替代解决方案是hosting.json在项目的根目录中使用 a 。

{
  "urls": "http://localhost:60000"
}

And then in Program.cs

然后在 Program.cs

public static void Main(string[] args)
{
    var config = new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory())
        .AddJsonFile("hosting.json", true)
        .Build();

    var host = new WebHostBuilder()
        .UseKestrel(options => options.AddServerHeader = false)
        .UseConfiguration(config)
        .UseContentRoot(Directory.GetCurrentDirectory())
        .UseIISIntegration()
        .UseStartup<Startup>()
        .Build();

    host.Run();
}

回答by Random

You can specify hosting URL without any changes to your app.

您可以指定托管 URL,而无需对您的应用程序进行任何更改。

Create a Properties/launchSettings.jsonfile in your project directory and fill it with something like this:

Properties/launchSettings.json在您的项目目录中创建一个文件并用如下内容填充它:

{
  "profiles": {
    "MyApp1-Dev": {
        "commandName": "Project",
        "environmentVariables": {
            "ASPNETCORE_ENVIRONMENT": "Development"
        },
        "applicationUrl": "http://localhost:5001/"
    }
  }
}

dotnet runcommand should pick your launchSettings.jsonfile and will display it in the console:

dotnet run命令应该选择您的launchSettings.json文件并将其显示在控制台中:

C:\ProjectPath [master ≡]
λ  dotnet run
Using launch settings from C:\ProjectPath\Properties\launchSettings.json...
Hosting environment: Development
Content root path: C:\ProjectPath
Now listening on: http://localhost:5001
Application started. Press Ctrl+C to shut down. 

More details: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/environments

更多详情:https: //docs.microsoft.com/en-us/aspnet/core/fundamentals/environments

回答by jabu.hlong

If using dotnet run

如果使用 dotnet run

dotnet run --urls="http://localhost:5001"

回答by oudi

Above .net core 2.2 the method Main support args with WebHost.CreateDefaultBuilder(args)

.net core 2.2 以上的方法 Main 支持 args 和 WebHost.CreateDefaultBuilder(args)

public class Program
{
    public static void Main(string[] args)
    {
        CreateWebHostBuilder(args).Build().Run();
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>();
}

You can build your project and go to binrun command like this

您可以构建您的项目并bin像这样运行命令

dotnet <yours>.dll --urls=http://localhost:5001

or with multi-urls

或多网址

dotnet <yours>.dll --urls="http://localhost:5001,https://localhost:5002"

回答by R. van Diesen

When hosted in docker containers (linux version for me), you might get a 'Connection Refused' message. In that case you can use IP address 0.0.0.0which means "all IP addresses on this machine" instead of the localhostloopback to fix the port forwarding.

当托管在 docker 容器(我是 linux 版本)中时,您可能会收到“连接被拒绝”消息。在这种情况下,您可以使用 IP 地址0.0.0.0,这意味着“本机上的所有 IP 地址”而不是localhost环回来修复端口转发。

public class Program
{
    public static void Main(string[] args)
    {
        var host = new WebHostBuilder()
            .UseKestrel()
            .UseContentRoot(Directory.GetCurrentDirectory())
            .UseIISIntegration()
            .UseStartup<Startup>()
            .UseUrls("http://0.0.0.0:5000/")
            .Build();

        host.Run();
    }
}

回答by Mwiza

Alternatively, you can specify port by running app via command line.

或者,您可以通过命令行运行应用程序来指定端口。

Simply run command:

只需运行命令:

dotnet run --server.urls http://localhost:5001

Note: Where 5001 is the port you want to run on.

注意:其中 5001 是您要运行的端口。

回答by Ernest

On .Net Core 3.1 just follow Microsoft Doc that it is pretty simple: kestrel-aspnetcore-3.1

在 .Net Core 3.1 上,只需按照 Microsoft Doc 操作即可,这非常简单:kestrel-aspnetcore-3.1

To summarize:

总结一下:

  1. Add the below ConfigureServices section to CreateDefaultBuilder on Program.cs:

    // using Microsoft.Extensions.DependencyInjection;
    
    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureServices((context, services) =>
            {
                services.Configure<KestrelServerOptions>(
                    context.Configuration.GetSection("Kestrel"));
            })
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            });
    
  2. Add the below basic config to appsettings.jsonfile (more config options on Microsoft article):

    "Kestrel": {
        "EndPoints": {
            "Http": {
                "Url": "http://0.0.0.0:5002"
            }
        }
    }
    
  3. Open CMD or Console on your project Publish/Debug/Release binaries folder and run:

    dotnet YourProject.dll
    
  4. Enjoy exploring your site/api at your http://localhost:5002

  1. 将以下 ConfigureServices 部分添加到 CreateDefaultBuilder 上Program.cs

    // using Microsoft.Extensions.DependencyInjection;
    
    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureServices((context, services) =>
            {
                services.Configure<KestrelServerOptions>(
                    context.Configuration.GetSection("Kestrel"));
            })
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            });
    
  2. 将以下基本配置添加到appsettings.json文件(Microsoft 文章中的更多配置选项):

    "Kestrel": {
        "EndPoints": {
            "Http": {
                "Url": "http://0.0.0.0:5002"
            }
        }
    }
    
  3. 在您的项目 Publish/Debug/Release binaries 文件夹中打开 CMD 或 Console 并运行:

    dotnet YourProject.dll
    
  4. 享受在您的http://localhost:5002浏览您的站点/api