本地主机中我的 API 运行 的自定义端口号

Custom port number for my API running in localhost

我有我的 API,它 运行 在本地主机的 8000 端口下。但是我只想知道是否可以 运行 我的 API我想要的端口(比如端口 1200、端口 5000 等)。或者有没有特定的端口,其中只有我可以选择一个到运行我的API。我是这个网络开发的新手,因此是这个基本问题的新手。

是的,没关系!请务必远离 MySQL (3306) 等常见端口。

一般来说,5000 是我见过的 .NET 开发人员使用最多的。有很多方法可以做到!

通过启动设置:

{
  "$schema": "http://json.schemastore.org/launchsettings.json",
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:63902",
      "sslPort": 44305
    }
  },
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": false,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "Brevity.Api": {
      "commandName": "Project",
      "launchBrowser": false,
      "applicationUrl": "https://localhost:5001;http://localhost:5000",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}

或通过Program.cs

public static IWebHostBuilder CreateWebHostBuilder(string[] args)
        {
            return WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>()
                .UseKestrel(options =>
                {
                    options.AddServerHeader = false;

                    // options.Listen(IPAddress.Any, 8080);         // http:*:80

                    var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
                    var isDevelopment = environment == Environments.Development;
                    var validateSSL = !string.IsNullOrEmpty(Environment.GetEnvironmentVariable("SSLCERT_PATH"));

                    // HTTPS Configuration
                    if (!System.Diagnostics.Debugger.IsAttached && !isDevelopment && validateSSL)
                    {
                        var hasHttpsPortConfigured = int.TryParse(Environment.GetEnvironmentVariable("HTTPS_PORT")
                            , out var httpsPort);
                        if (!hasHttpsPortConfigured)
                        {
                            httpsPort = 5001; // Default port

                            Console.WriteLine("HTTPS port not configured! Self configuring to 5001.");
                        }

                        var certPath = Environment.GetEnvironmentVariable("SSLCERT_PATH");

                        var certPassword = Environment.GetEnvironmentVariable("SSLCERT_PASSWORD");

                        options.Listen(IPAddress.Any, httpsPort, listenOptions =>
                        {
                            var cert = new X509Certificate2(certPath, certPassword);

                            listenOptions.UseHttps(cert);
                        });
                    }
                });
        }

很高兴您使用的是 .NET Core。我们才刚刚开始成为最好的编程语言之一!