.net core发布到windows服务

vscode开发

dotnet new webapi -minimal -o TodoApi
cd TodoApi
code -r ../TodoApi
dotnet add package Microsoft.Extensions.Hosting.WindowsServices

完整代码

using Microsoft.Extensions.Hosting.WindowsServices;

var options = new WebApplicationOptions
{
    Args = args,
    ContentRootPath = WindowsServiceHelpers.IsWindowsService() ? AppContext.BaseDirectory : default
};
var builder = WebApplication.CreateBuilder(options);
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Host.UseWindowsService(); 

var app = builder.Build();
/*if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}*/

app.UseSwagger();
app.UseSwaggerUI();


app.UseHttpsRedirection();

var summaries = new[]
{
    "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};

app.MapGet("/weatherforecast", () =>
{
    var forecast =  Enumerable.Range(1, 5).Select(index =>
        new WeatherForecast
        (
            DateTime.Now.AddDays(index),
            Random.Shared.Next(-20, 55),
            summaries[Random.Shared.Next(summaries.Length)]
        ))
        .ToArray();
    return forecast;
})
.WithName("GetWeatherForecast");

await app.RunAsync("http://127.0.0.1:5001");

record WeatherForecast(DateTime Date, int TemperatureC, string? Summary)
{
    public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
}

powershell

New-Service -Name mytest -BinaryPathName "D:\GIT\ASP.NET.TEST\TodoApi\bin\Debug\net6.0\win-x64\publish\TodoApi.exe" -Description "mytest " -DisplayName "mytest" -StartupType Automatic


Start-Service mytest

参考:

  • 教程:使用 ASP.NET Core 创建最小 Web API
  • .NET6 Minimal APIs 开发实践

你可能感兴趣的:(c#,.netcore,windows,microsoft)