繁体   English   中英

自托管 Net Core 3 应用程序不采取端口设置

[英]Self-hosted Net Core 3 application does not take port settings

我觉得问这个很傻,因为有很多关于 Net Core 托管的文章,但我已经尝试了所有方法,但仍然有问题。

我正在尝试更改自托管 Web 服务使用的端口。 我已经更改了 launchSettings.json 文件。

"MyService": {
      "commandName": "Project",
      "environmentVariables": {
        "ASPNETCORE_URLS": "http://*:51248",
        "ASPNETCORE_ENVIRONMENT": "Development"
      },
      "applicationUrl": "http://localhost:51248"
    },
    "MyService": {
      "commandName": "Project",
      "environmentVariables": {
        "ASPNETCORE_URLS": "http://*:51248",
        "ASPNETCORE_ENVIRONMENT": "Release"
      },
      "applicationUrl": "http://localhost:51248"
    }

我还尝试通过直接配置设置端口:

public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureServices((hostContext, services) =>
                {
                    services.AddHostedService<MyServiceWorker>();
                })
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseUrls("http://*:51248");
                    webBuilder.UseStartup<Startup>();
                })
                .ConfigureWebHost(config => { config.UseUrls("http://*:51248"); })
                .UseWindowsService()
                .UseSerilog();
    }

如果我通过 Visual Studio 运行一切正常,但如果我直接运行可执行文件,它仍然使用端口 5000。如果我将它作为 Windows 服务运行,它似乎选择了一些随机端口。

我打了几十个网站,但没有找到解决方案。 有没有人有什么建议?

我觉得很愚蠢,但我会发布这个以防它对其他人有帮助。 我发现如果应用程序作为 Windows 服务运行, .UseUrls确实有效。 从 Visual Studio 中启动时, launchSettings.json设置有效。 仅作为控制台应用程序运行时,我无法更改侦听端口。

事实证明,问题是我测试应用程序的方式造成的。 希望没有其他人会浪费很多时间做同样的事情。

可以有很多选择,其中之一来自这里

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

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

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                    webBuilder.ConfigureKestrel(serverOptions =>
                    {
                        serverOptions.Listen(IPAddress.Any, 51248);
                    });
                });
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM