Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

454
Vistas
ASP.NET Core .NET 6 Vista previa 7 Servicio de Windows

Creé un nuevo proyecto ASP.NET Core con Visual Studio 2022 Preview y estoy tratando de ejecutarlo como un servicio de Windows. Descargué el último paquete Microsoft.Extensions.Hosting.WindowsServices (6.0.0-preview.7.21377.19).

Al investigar en línea, la función .UseWindowsService() entra en el método CreateHostBuilder. Pero en la nueva plantilla se ve diferente. No puedo entender dónde debo llamar a .UseWindowsService en la nueva plantilla. Este es mi código actual, parece que el servicio se está iniciando, pero luego, cuando busco localhost: 5000, aparece el error 404

 using Microsoft.OpenApi.Models; using Microsoft.Extensions.Hosting.WindowsServices; var builder = WebApplication.CreateBuilder(args); builder.Host.UseWindowsService(); // <--- Added this line // Add services to the container. builder.Services.AddControllers(); builder.Services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new() { Title = "MyWindowsService", Version = "v1" }); }); var app = builder.Build(); // Configure the HTTP request pipeline. if (builder.Environment.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseSwagger(); app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "MyWindowsService v1")); } app.UseAuthorization(); app.MapControllers(); app.Run();

Publiqué mi service exe así

 dotnet publish -c Release -r win-x64 --self-contained
over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

La siguiente codificación establece el tiempo de vida en WindowsServiceLifetime y habilita el registro en el registro de eventos. En la mayoría de los casos, esto debería ser todo lo que necesita para ejecutar la aplicación como un servicio de Windows.

 if (WindowsServiceHelpers.IsWindowsService()) { appBuilder.Services.AddSingleton<IHostLifetime, WindowsServiceLifetime>(); appBuilder.Logging.AddEventLog(settings => { if (string.IsNullOrEmpty(settings.SourceName)) { settings.SourceName = appBuilder.Environment.ApplicationName; } }); }
over 4 years ago · Santiago Trujillo Denunciar

0

Ya que simplemente usando

 builder.Host.UseWindowsService();

no funcionará con WebApplication.CreateBuilder() ( ver ), sino que lanzará la excepción

 Exception Info: System.NotSupportedException: The content root changed from "C:\Windows\system32\" to "...". Changing the host configuration using WebApplicationBuilder.Host is not supported. Use WebApplication.CreateBuilder(WebApplicationOptions) instead.

o más bien causará este error

 Start-Service : Service 'Service1 (Service1)' cannot be started due to the following error: Cannot start service Service1 on computer '.'.

al intentar iniciar el servicio con Start-Service en PowerShell, encontré una solución que funcionó para mí

 using Microsoft.Extensions.Hosting.WindowsServices; var options = new WebApplicationOptions { Args = args, ContentRootPath = WindowsServiceHelpers.IsWindowsService() ? AppContext.BaseDirectory : default }; var builder = WebApplication.CreateBuilder(options); builder.Host.UseWindowsService();

aquí: una aplicación de API web central de asp.net, que usa "UseWindowsService", informa un error "System.NotSupportedException: la raíz del contenido cambió. No se admite el cambio de la configuración del host ”al iniciar el servicio

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda