.net Windows无法在本地计算机上提供服务

wsxa1bj1  于 2023-10-21  发布在  .NET
关注(0)|答案(1)|浏览(166)

我面临的问题上启动服务找到下面的附件.我用的是Dot net7
enter image description here

public static void Main(string[] args)
  {
          ipAddress = "127.0.0.1";
          var result = CreateHostBuilder(args).Build();
          result.Run();
      
  }
  public static Microsoft.Extensions.Hosting.IHostBuilder CreateHostBuilder(string[] args) =>

 Host.CreateDefaultBuilder(args)
     .ConfigureWebHostDefaults(webBuilder =>
     {
         webBuilder.UseStartup<Startup>();
         webBuilder.UseKestrel(options =>
         {
             options.Listen(IPAddress.Parse("127.0.0.1"), 8989, configure =>
             {
                 configure.Protocols = HttpProtocols.Http1AndHttp2;
                 configure.UseHttps(opt => opt.SslProtocols = SslProtocols.Tls12 | SslProtocols.Tls13);
             });
         });

     }).UseWindowsService(sn => sn.ServiceName = "Test Service");`

我正在尝试使用cmd行sc create“Test Service”binPath =“D:\Test.exe”在cmd提示符下运行

g6ll5ycj

g6ll5ycj1#

我测试了你的代码来生成一个服务。也许你也有同样的问题。
EventViewer-System

EventViewer-Application

好吧,我没有通过建议的命令解决这个问题。但是在.net7中,你可以用另一种方式编写代码。
软件包Microsoft.Extensions.Hosting.WindowsService program.cs

using System.Security.Authentication;

internal class Program
{
    private static void Main(string[] args)
    {
        var builder = WebApplication.CreateBuilder(args);

        builder.WebHost.ConfigureKestrel(serverOptions =>
        {
            serverOptions.ConfigureHttpsDefaults(listenOptions =>
            {
                listenOptions.SslProtocols = SslProtocols.Tls12 | SslProtocols.Tls13;
            });
        });

        builder.Services.AddWindowsService();

        var app = builder.Build();

        app.MapGet("/", () => "Hello World!");
        app.Run();
    }
}

appsettings.json(在此处配置端口并选择证书)

"Kestrel": {
    "Endpoints": {
      "Http": {
        "Url": "http://*:8988"
      },
      "Https": {
        "Url": "https://*:8989",
        "Certificate": {
          "Subject": "localhost",
          "Store": "My",
          "Location": "LocalMachine",
          "AllowInvalid": "true"
        }
      }
    }
  },

发布和创建服务。
sc create TestService4 binPath=E:\TESTS\TestService\TestService\bin\Release\net7.0\publish\TestService.exe
启动和测试

从主题中选择证书



参考:https://learn.microsoft.com/en-us/aspnet/core/fundamentals/servers/kestrel/endpoints?view=aspnetcore-7.0#replace-the-default-certificate-from-configuration

相关问题