本文以创建的WebAPI项目为例子进行讲解(本人使用VS Code创建的项目)
1、使用VS Code创建WebAPI项目(项目名称自定义)
2、在创建的项目csproj项目文件中,确认是否存在运行时标识符,或将其添加到包含目标框架的 <PropertyGroup> 中
<PropertyGroup>
<TargetFramework>netcoreapp2.0</TargetFramework>
<RuntimeIdentifier>win10-x64</RuntimeIdentifier>
</PropertyGroup>
3、为 Microsoft.AspNetCore.Hosting.WindowsServices 添加包引用
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.6" />
<PackageReference Include="Microsoft.AspNetCore.Hosting.WindowsServices" Version="2.1.0"/>
</ItemGroup>
4、Program文件 添加如下引用
using System.Diagnostics;
using Microsoft.AspNetCore.Hosting.WindowsServices;
将代码修改为
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().RunAsService();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args)
{
var pathToExe = Process.GetCurrentProcess().MainModule.FileName;
var pathToContentRoot = Path.GetDirectoryName(pathToExe);
return WebHost.CreateDefaultBuilder(args)
.UseContentRoot(pathToContentRoot)
.UseStartup<Startup>();
}
5、发布项目,使用sc命令创建服务
以管理员身份运行命令提示符,输入sc 相关命令——sc create <SERVICE_NAME> binPath= "<PATH_TO_SERVICE_EXECUTABLE>",binPath值是应用的可执行文件的路径,其中包括可执行文件的文件名
示例: