Kestrel封装在WindowService中(.net5,.net6,.net7三个版本的介绍)

Kestrel封装在WindowServer中

  • 背景
  • 关于WindowsServer
  • 开发服务
    • .NET5版本
      • 建项目
      • 添加Controller
      • 添加引用
      • 修改Startup.cs
      • 修改Program.cs
      • 配置Kestrel监听
      • 发布程序
      • 通过命令行创建服务
        • 关于SC命令
      • 启动服务查看效果
        • 测试效果
    • ==.NET6==
      • 错误1
      • 解决办法:
      • 错误2
      • 运行效果如下图
    • .NET7版本(和6版本一样就可以)
  • 源码下载

背景

在一些开发过程中,会在局域网内搭建webapi服务作为移动端的服务接口使用,但是每次实施人员要到客户现场安装iis等工具,还有一些web的配置,非常繁琐,所以想着把webapi封装到WindowService中,可以通过自定义的安装程序进行一键部署,岂不美哉!
这篇文章主要是记录如何将Kestrel的服务封装在WindowService中

关于WindowsServer

请参考如下这篇文章

.netcore worker service (辅助角色服务) 的上手入门,包含linux和windows服务部署

开发服务

之前做过.net5版本的处理,觉得挺简单的,但是到.net6的时候遇到了一些问题,所以下面都会记录

.NET5版本

建项目

新建一个webapi项目,如下图
Kestrel封装在WindowService中(.net5,.net6,.net7三个版本的介绍)_第1张图片

添加Controller

Kestrel封装在WindowService中(.net5,.net6,.net7三个版本的介绍)_第2张图片

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace WebApiNet_v5.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class TestController : ControllerBase
    {
        [HttpGet]
        public string Get(string name)
        {
            return $"Hello {name}";
        }
    }
}

添加引用

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>net5.0-windows</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
  <!-- 千万不要引用7.0版本,不兼容 -->
    <PackageReference Include="Microsoft.Extensions.Hosting.WindowsServices" Version="6.0.0" />
    <PackageReference Include="Swashbuckle.AspNetCore" Version="5.6.3" />
  </ItemGroup>

</Project>

修改Startup.cs

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.OpenApi.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace WebApiNet_v5
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {

            services.AddControllers();
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo { Title = "WebApiNet_v5", Version = "v1" });
            });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
        //这里注释一下是为了在发布以后还可以查看Swagger
            //if (env.IsDevelopment())
            //{
                app.UseDeveloperExceptionPage();
                app.UseSwagger();
                app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "WebApiNet_v5 v1"));
            //}

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}

修改Program.cs

using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;

namespace WebApiNet_v5
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                })
            //添加服务
            .UseWindowsService(cfg =>
            {
                cfg.ServiceName = "WebApiNet_v5";
            })

            ;
    }
}

配置Kestrel监听

参考文章

.Net Core 通过配置文件(appsetting.json)修改Kestrel启动端口

实际配置效果

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "Kestrel": {
    "EndPoints": {
      "Http": {
        "Url": "http://0.0.0.0:5003" // 端口自己改吧
      }
    }
  },
  "AllowedHosts": "*"
}

发布程序

发布到本地目录,如下图
Kestrel封装在WindowService中(.net5,.net6,.net7三个版本的介绍)_第3张图片

通过命令行创建服务

注意:一定要以管理员身份运行,否则无权限
例如出现如下错误:
[SC] OpenSCManager 失败 5:
在这里插入图片描述

关于SC命令

Kestrel封装在WindowService中(.net5,.net6,.net7三个版本的介绍)_第4张图片

启动服务查看效果

sc.exe start 1_v5

测试效果

Kestrel封装在WindowService中(.net5,.net6,.net7三个版本的介绍)_第5张图片


.NET6

因为.net6的改版,已经没有Startup文件了,而且程序的启动已经不再使用IHostBuilder接口了。
所以如下记录的内容都是在.net5版本上的差异与变动
代码如下:

using Microsoft.Extensions.Hosting.WindowsServices;
using Microsoft.Extensions.Options;
using Microsoft.OpenApi.Models;
using System.Net;

namespace WebApiNet_v6
{
    public class Program
    {
        public static void Main(string[] args)
        {
        //配置启动参数
            var options = new WebApplicationOptions
            {
                Args = args,
                ContentRootPath = WindowsServiceHelpers.IsWindowsService()
                                     ? AppContext.BaseDirectory : default
            };

            var builder = WebApplication.CreateBuilder(options);

            // 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();
//启动服务
            builder.Host.UseWindowsService();

            var app = builder.Build();

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

            //app.UseHttpsRedirection();

            app.UseAuthorization();

            app.MapControllers();

            app.Run();
        }
    }
}

代码上的调整就这么多,但是在修改的过程中遇到了一些错误

错误1

出现 URL scheme must be http or https for CORS request

Kestrel封装在WindowService中(.net5,.net6,.net7三个版本的介绍)_第6张图片

解决办法:

禁用https重定向,或者完全使用https都可以
禁用办法就是注释这行代码

//app.UseHttpsRedirection();

错误2

安装了服务怎么都无法开启
Kestrel封装在WindowService中(.net5,.net6,.net7三个版本的介绍)_第7张图片

解决办法:因为没有证书,所以不配置https的终结点就可以了。

运行效果如下图

Kestrel封装在WindowService中(.net5,.net6,.net7三个版本的介绍)_第8张图片

.NET7版本(和6版本一样就可以)

源码下载

https://download.csdn.net/download/iml6yu/87377783

在 Windows 服务中托管 ASP.NET Core

你可能感兴趣的:(ASP.NET,NetCore,.net,microsoft,windows)