从Windows服务启动ASP.NET核心API

lkaoscv7  于 2022-12-15  发布在  .NET
关注(0)|答案(1)|浏览(175)

我在Visual Studio 22中使用ASP.NET核心API模板创建了一个小API,目标是.NET6。为了测试/调试,我使用控制台应用程序启动API,一切正常。但为了生产,我需要从Windows服务启动此API,但我不知道如何制作。
我可以简单地把.exe文件放在服务所在的文件夹中并调用它,但目前为止,如果没有用户登录,控制台应用程序将不会启动。因此,我们的想法是将API与所有服务打包在一起,并在Windows服务启动时启动它。
我做了一个小测试,创建了一个静态类名“Test.cs”,方法名为“Start”,从“Program.cs”复制所有代码,并从测试应用程序调用“Start”方法。API启动并保持侦听端点,但由于某种原因,没有从项目控制器文件夹Map控制器。
all OK when starting API from default
controllers not mapped when start API from static method
program.cs

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

//to avoid json serialize camel casing

builder.Services.AddControllers().AddJsonOptions(opts => 
{ 
    opts.JsonSerializerOptions.PropertyNamingPolicy = null;
    opts.JsonSerializerOptions.NumberHandling = System.Text.Json.Serialization.JsonNumberHandling.AllowNamedFloatingPointLiterals; //para aceitar NAN, infinitos etc no json
});
//////////

//Nedeed
builder.Services.AddCors(options =>
{
    options.AddPolicy("CorsPolicy", builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
});


var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();
app.UseCors("CorsPolicy");

//app.UseAuthorization();

app.MapControllers();

app.Run();

test.cs

namespace ProjectX.Api
{
    public static class Test
    {

        public static void Start()
        {
            var builder = WebApplication.CreateBuilder();

            // Add services to the container.

            builder.Services.AddControllers();
            // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
            builder.Services.AddEndpointsApiExplorer();
            builder.Services.AddSwaggerGen();

            //to avoid json serialize camel casing

            builder.Services.AddControllers().AddJsonOptions(opts =>
            {
                opts.JsonSerializerOptions.PropertyNamingPolicy = null;
                opts.JsonSerializerOptions.NumberHandling = System.Text.Json.Serialization.JsonNumberHandling.AllowNamedFloatingPointLiterals; //para aceitar NAN, infinitos etc no json
            });
            //////////

            //Nedeed
            builder.Services.AddCors(options =>
            {
                options.AddPolicy("CorsPolicy", builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
            });


            var app = builder.Build();


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

            app.UseHttpsRedirection();
            app.UseCors("CorsPolicy");

            //app.UseAuthorization();

            app.MapControllers();

            app.Run();

        }

    }
}

测试程序

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace ProjectX.Tester
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            try
            {

                ProjectX.Api.Test.Start();
            }
            catch (Exception ex )
            {

            }
        }
    }
}

mnemlml8

mnemlml81#

您可以直接在Start()中运行Web API的exe文件:

public static void Start()
{
    ProcessStartInfo startInfo = new ProcessStartInfo();
    startInfo.CreateNoWindow = false;
    startInfo.UseShellExecute = false;
    startInfo.FileName = "Your Path\\ProjectName.exe";
    startInfo.WindowStyle = ProcessWindowStyle.Normal;
    startInfo.Arguments = "";
    try
    {
        using (Process exeProcess = Process.Start(startInfo))
        {
            exeProcess.WaitForExit();
        }
    }
    catch
    {
        //Log error.
    }
}

然后就可以成功调用项目中的API了:

如果要应用Swagger,请在生产环境Program.cs中添加以下代码:

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

结果:

希望这对你有帮助。

相关问题