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

这篇具有很好参考价值的文章主要介绍了Kestrel封装在WindowService中(.net5,.net6,.net7三个版本的介绍)。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

背景

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

关于WindowsServer

请参考如下这篇文章

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

开发服务

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

.NET5版本

建项目

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

添加Controller

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

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三个版本的介绍)

通过命令行创建服务

注意:一定要以管理员身份运行,否则无权限
例如出现如下错误:
[SC] OpenSCManager 失败 5:
Kestrel封装在WindowService中(.net5,.net6,.net7三个版本的介绍)

关于SC命令

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

启动服务查看效果

sc.exe start 1_v5
测试效果

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


.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三个版本的介绍)

解决办法:

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

//app.UseHttpsRedirection();

错误2

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

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

运行效果如下图

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

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

源码下载

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

在 Windows 服务中托管 ASP.NET Core文章来源地址https://www.toymoban.com/news/detail-482595.html

到了这里,关于Kestrel封装在WindowService中(.net5,.net6,.net7三个版本的介绍)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • net6支持的windows版本

    微软官方文档https://learn.microsoft.com/zh-cn/dotnet/core/install/windows?tabs=net60 .NET 6 支持下列 Windows 版本: (OS)-------------------------------------Version-----------------------体系结构 Windows 11---------------------------21H2--------------------------x64、Arm64 Windows 10 客户端 -----------------1607±-----------------------x

    2024年02月07日
    浏览(29)
  • .Net6 Web Core API --- AOP -- log4net 封装 -- MySQL -- txt

    目录 一、引入 NuGet 包 二、配置log4net.config   三、编写Log4net封装类 四、编写日志记录类 五、AOP -- 拦截器 -- 封装 六、案例编写 七、结果展示 log4net  Microsoft.Extensions.Logging.Log4Net.AspNetCore    MySql.Data         ----  MySQL数据库需要 Newtonsoft.Json Autofac Autofac.Extensions.DependencyInj

    2024年02月14日
    浏览(37)
  • 使用Autofac进行服务注册,适用版本.Net6(程序集、泛型)

    具体的也可以去参考官网:https://autofac.readthedocs.io/en/latest/integration/aspnetcore.html 首先在Program.cs所属的层中引用nuget包: nuget网址:https://www.nuget.org/packages  可以使用NuGet包管理器进行搜索安装 在Program.cs中加入如下代码: 代码中SmartHealthcare.Application可以替换为具体自己项目中Ap

    2024年02月16日
    浏览(36)
  • .NET6 独立模式部署应用程序(无需客户机安装指定版本.NET运行时)

    下图对于.NET开发人员一定不陌生,尤其是CS架构,客户电脑要运行基于.NET开发的程序,无论是使用C#,还是VB.NET、F#,发布后的程序的运行环境都需要有相应版本的.NET的运行时,否则应用程序将无法正常运行。 BS架构下,在服务器上安装指定版本.NET运行时,工作量可以忽略不

    2024年02月11日
    浏览(43)
  • Kestrel封装在Winform中

    另外一篇文章 Kestrel封装在WindowService中(.net5,.net6,.net7三个版本的介绍) 在很久以前为了满足需求,已经开发了一款winform程序,并且是4.6.1版本的,如今为了和第三方对接,需要在这个winform上提供WebAPI的接口。因为第三方的程序是一份没有源码的程序。 网上有很多自写web服

    2024年02月04日
    浏览(27)
  • 什么是 .Net5?.Net5和.Net Core 有什么关系?

    2021年即将结束,使用 .net开发已经有多年的经验,微软自2016年发布 .net core1.0 之后,.net core的热度蒸蒸日上,asp.net core3.1 的性能以及稳定性也超越了java,特别是云原生开发这一块,看的出 .net core有很好的前景,但目前国内的热度不够,大部分公司还是在使用.net framework ,而

    2024年02月11日
    浏览(22)
  • .NET5从零基础到精通:全面掌握.NET5开发技能

    C#版本新语法-官网: C#7:https://docs.microsoft.com/zh-cn/dotnet/csharp/whats-new/csharp-7 C#8:https://docs.microsoft.com/zh-cn/dotnet/csharp/whats-new/csharp-8 C#9:https://docs.microsoft.com/zh-cn/dotnet/csharp/whats-new/csharp-9 章节 第一章:https://www.cnblogs.com/kimiliucn/p/17613434.html 第二章:https://www.cnblogs.com/kimiliucn/p

    2024年02月14日
    浏览(22)
  • 记录一次.NET6环境使用Visual Studio 2022 V17.6.2版本的异常

    C#开发环境Visual Studio 2022 V17.6.2版本。 .NET 6.0 系统是Blazor Server框架的系统页面,在使用Visual Studio 2022 V17.6.2版本编译后,执行出现: 先使用了Visual Studio 2022 V17.4.0版本编译后可以正常。 经过分析:Visual Studio 2022 V17.4.0还在使用的目标框架为:.NET 6.0,Visual Studio 2022 V17.6.2版本的

    2024年02月08日
    浏览(50)
  • .NET5从零基础到精通:全面掌握.NET5开发技能【第一章】

    C#版本新语法-官网: C#7:https://docs.microsoft.com/zh-cn/dotnet/csharp/whats-new/csharp-7 C#8:https://docs.microsoft.com/zh-cn/dotnet/csharp/whats-new/csharp-8 C#9:https://docs.microsoft.com/zh-cn/dotnet/csharp/whats-new/csharp-9 章节 第一章:https://www.cnblogs.com/kimiliucn/p/17613434.html 第二章:https://www.cnblogs.com/kimiliucn/p

    2024年02月13日
    浏览(59)
  • .NET5从零基础到精通:全面掌握.NET5开发技能【第二章】

    章节 第一章:https://www.cnblogs.com/kimiliucn/p/17613434.html 第二章:https://www.cnblogs.com/kimiliucn/p/17620153.html 第三章:https://www.cnblogs.com/kimiliucn/p/17620159.html 5.1-使用Session 5.2-Log4Net组件使用 (1)管理Nuget程序,下载【log4net】和【Microsoft.Extensions.Logging.Log4Net.AspNetCore】 (2)新建一个文件

    2024年02月13日
    浏览(37)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包