.Net Core 项目在Windows服务中托管【转载】

本文以创建的WebAPI项目为例子进行讲解(本人使用VS Code创建的项目)

1、使用VS Code创建WebAPI项目(项目名称自定义)

2、在创建的项目csproj项目文件中,确认是否存在运行时标识符,或将其添加到包含目标框架的 <PropertyGroup> 中

  1.  
    <PropertyGroup>
  2.  
    <TargetFramework>netcoreapp2 .0</TargetFramework>
  3.  
    <RuntimeIdentifier>win10-x64</RuntimeIdentifier>
  4.  
    </PropertyGroup>

3、为 Microsoft.AspNetCore.Hosting.WindowsServices 添加包引用

  1.  
    <ItemGroup>
  2.  
    <PackageReference Include= "Microsoft.AspNetCore.All" Version="2.0.6" />
  3.  
    <PackageReference Include= "Microsoft.AspNetCore.Hosting.WindowsServices" Version="2.1.0"/>
  4.  
    </ItemGroup>

4、Program文件 添加如下引用

  1.  
    using System.Diagnostics;
  2.  
    using Microsoft.AspNetCore.Hosting.WindowsServices;

将代码修改为

  1.  
    public static void Main(string[] args)
  2.  
    {
  3.  
    CreateWebHostBuilder(args).Build().RunAsService();
  4.  
    }
  5.  
     
  6.  
    public static IWebHostBuilder CreateWebHostBuilder(string[] args)
  7.  
    {
  8.  
    var pathToExe = Process.GetCurrentProcess().MainModule.FileName;
  9.  
    var pathToContentRoot = Path.GetDirectoryName(pathToExe);
  10.  
     
  11.  
    return WebHost.CreateDefaultBuilder(args)
  12.  
    .UseContentRoot(pathToContentRoot)
  13.  
    .UseStartup<Startup>();
  14.  
    }

5、发布项目,使用sc命令创建服务

以管理员身份运行命令提示符,输入sc 相关命令——sc create <SERVICE_NAME> binPath= "<PATH_TO_SERVICE_EXECUTABLE>",binPath值是应用的可执行文件的路径,其中包括可执行文件的文件名

示例:

6、在服务中找到创建的服务,启动后,使用Postman 进行测试

--------------------- 本文来自 蓝晶之心 的CSDN 博客 ,全文地址请点击:https://blog.csdn.net/liwan09/article/details/81740090?utm_source=copy 

猜你喜欢

转载自www.cnblogs.com/yy1234/p/9707901.html