寫在前面
前面寫了一篇關(guān)于將.NET應(yīng)用轉(zhuǎn)換成Windows服務(wù)的方法,其實(shí)真正的目的是為了探索如何將Asp.Net Core Web Api 部署成Windows 服務(wù)。基于上一篇的基礎(chǔ),只需把創(chuàng)建 WebApplication 的代碼放到?BackgroundService 的ExecuteAsync方法中即可。
其中比較重要的一個(gè)細(xì)節(jié)就是需要指定一下配置:
? ? ? ? host.ConfigureAppConfiguration((hostingContext, config) => {
? ? ? ? ? ? config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
? ? ? ? ? ? config.AddEnvironmentVariables();
? ? ? ? });
appsettings.json 的內(nèi)容如下:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"urls": "http://localhost:6001",
"server.urls": "http://localhost:6001"
}
重點(diǎn)部分:
? "urls": "http://localhost:6001",
? "server.urls": "http://localhost:6001"?
代碼實(shí)現(xiàn)
using System.Runtime.InteropServices;
using System.Text.Json.Serialization;
using Microsoft.Extensions.Hosting;
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args)
{
var host = Host.CreateDefaultBuilder(args);
//判斷當(dāng)前系統(tǒng)是否為windows
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
host.UseWindowsService();
}
host.ConfigureAppConfiguration((hostingContext, config) => {
config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
config.AddEnvironmentVariables();
});
return host.ConfigureServices((hostContext, services) =>
{
services.AddHostedService<WebApp>();
});
}
}
public class WebApp: BackgroundService
{
public void StartApp()
{
var builder = WebApplication.CreateSlimBuilder([]);
builder.Services.ConfigureHttpJsonOptions(options =>
{
options.SerializerOptions.TypeInfoResolverChain.Insert(0, AppJsonSerializerContext.Default);
});
var app = builder.Build();
var sampleTodos = new Todo[] {
new(1, "Walk the dog"),
new(2, "Do the dishes", DateOnly.FromDateTime(DateTime.Now)),
new(3, "Do the laundry", DateOnly.FromDateTime(DateTime.Now.AddDays(1))),
new(4, "Clean the bathroom"),
new(5, "Clean the car", DateOnly.FromDateTime(DateTime.Now.AddDays(2)))
};
var todosApi = app.MapGroup("/todos");
todosApi.MapGet("/", () => sampleTodos);
todosApi.MapGet("/{id}", (int id) =>
sampleTodos.FirstOrDefault(a => a.Id == id) is { } todo
? Results.Ok(todo)
: Results.NotFound());
app.Run();
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
StartApp();
}
}
public record Todo(int Id, string? Title, DateOnly? DueBy = null, bool IsComplete = false);
[JsonSerializable(typeof(Todo[]))]
internal partial class AppJsonSerializerContext : JsonSerializerContext
{
}
?項(xiàng)目目錄結(jié)構(gòu):
運(yùn)行目錄結(jié)構(gòu):
?setup.bat 內(nèi)容:
sc create MyService binPath= %~dp0AspNetCoreWindowsService.exe
sc failure MyService actions= restart/60000/restart/60000/""/60000 reset= 86400
sc start MyService
sc config MyService start=auto
調(diào)用示例
執(zhí)行setup.bat?
服務(wù)被成功創(chuàng)建并運(yùn)行?
用瀏覽器訪問(wèn)一下
?文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-799150.html
?訪問(wèn)正常,到此結(jié)束。文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-799150.html
?
到了這里,關(guān)于如何將.NET 8.0的ASP.NET Core Web API部署成Windows服務(wù)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!