如何更改Asp.Net核心应用程序的端口号?

问题描述 投票:18回答:8

我在project.json中添加了以下部分。

  "commands": {
    "run": "run server.urls=http://localhost:8082",
    "web": "Microsoft.AspNet.Hosting --server Microsoft.AspNet.Server.Kestrel --server.urls http://localhost:8082",
    "weblistener": "Microsoft.AspNet.Hosting --server WebListener --server.urls http://localhost:8082"
  },

但是,当使用http://localhost:5000运行它时,它仍然显示“正在收听:dotnet myapp.dll”?

顺便说一下,来自其他机器的客户能否访问该服务?

asp.net-core .net-core
8个回答
27
投票

是的,如果您绑定任何外部IP地址,这将可从其他计算机访问。例如绑定到http://*:80。请注意,绑定到http://localhost:80只会绑定在127.0.0.1接口上,因此无法从其他计算机访问。

Visual Studio正在覆盖您的端口。您可以更改VS端口编辑此文件Properties\launchSettings.json或者通过代码设置它:

        var host = new WebHostBuilder()
            .UseKestrel()
            .UseContentRoot(Directory.GetCurrentDirectory())
            .UseIISIntegration()
            .UseStartup<Startup>()
            .UseUrls("http://*:80") // <-----
            .Build();

        host.Run();

here提供了使用外部配置文件的分步指南。


10
投票

在Asp.net core 2.0 WebApp中,如果您使用的是visual studio搜索LaunchSettings.json。我正在添加我的LaunchSettings.json,您可以更改端口号,因为您可以看到。

enter image description here


5
投票

在visual studio 2017中,我们可以从LaunchSetting.json更改端口号

在Properties-> LaunchSettings.json中。

打开LaunchSettings.json并更改端口号。

Launch

更改json文件中的端口号

enter image description here


3
投票

.UseUrls("http://*:80")中使用以下一行代码Program.cs 因此改变.UseStartup<Startup>().UseStartup<Startup>() .UseUrls("http://*:80")


1
投票

我们可以使用此命令通过Windows Powershell运行我们的主机项目,而不使用IIS和Visual Studio在单独的端口上。 krestel Web服务器的默认值为5001

$env:ASPNETCORE_URLS="http://localhost:22742" ; dotnet run

0
投票

你也可以像这样编码

        IConfiguration config  = new ConfigurationBuilder()
        .AddCommandLine(args)
        .Build(); 
        var host = new WebHostBuilder()
         .UseConfiguration(config)
         .UseKestrel()
         .UseContentRoot(Directory.GetCurrentDirectory()) 
         .UseStartup<Startup>()
         .Build();

并通过命令行设置应用程序:dotnet run --server.urls http:// *:5555


0
投票

转到program.cs文件添加UseUrs方法来设置你的url,确保你不使用保留的url或端口

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

        public static IWebHost BuildWebHost(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>()

                // params string[] urls
                .UseUrls(urls: "http://localhost:10000")

                .Build();
    }

0
投票

所有其他答案仅针对HTTP网址。如果URL是https,那么执行以下操作,

  1. 在API项目的Properties下打开launchsettings.jsonenter image description here
  2. sslPort下更改iisSettings -> iisExpress

样本launchsettings.json将如下所示

{
  "iisSettings": {
    "iisExpress": {
      "applicationUrl": "http://localhost:12345",
      "sslPort": 98765 <== Change_this
    }
  },
© www.soinside.com 2019 - 2024. All rights reserved.