.net core 版本:2.1
产生的问题:
按照官方的方式将ASP.NET Core部署成WINDOWS服务后,会报以下错误,因为是使用 dotnet.exe 来启动程序,启动目录定位到了c:windowssystem32下,暂时没有找到怎么切换到程序目录的方法。
Application: dotnet.exe CoreCLR Version: 4.6.28516.3 Description: The process was terminated due to an unhandled exception. Exception Info: System.IO.DirectoryNotFoundException: C:windowssystem32
解决方法:
1. NuGet引用 Microsoft.AspNetCore.Hosting.WindowsServices
2. 修改Main入口
public class Program
{
public static void Main(string[] args)
{
var isService = !(Debugger.IsAttached || args.Contains("--console"));
if (isService)
{
var pathToExe = Process.GetCurrentProcess().MainModule.FileName;
var pathToContentRoot = Path.GetDirectoryName(pathToExe);
Directory.SetCurrentDirectory(pathToContentRoot);
}
var builder = CreateWebHostBuilder(
args.Where(arg => arg != "--console").ToArray());
var host = builder.Build();
if (isService)
{
host.RunAsService();
}
else
{
host.Run();
}
}
private static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseKestrel()
.ConfigureAppConfiguration((context, builder) =>
{
builder.SetBasePath(context.HostingEnvironment.ContentRootPath)
.AddDefaultJsonFile()
.AddEnvironmentJsonFile();
})
.UseStartup();
}
3. 修改发布设置
将目标运行时改为'win-x64'(或者win-x84),这样发布时会生成 .exe 文件(这个很重要,这样用EXE启动就解决了启动目录定位的问题),可移植方式生成的是 .dll。
4. 服务安装、启动
//安装服务 sc create MyService binPath= ""D:App1MyService.exe" """ DisplayName= "MyService" start= auto //启动服务: sc run MyService //停止服务: sc stop MyService //卸载服务: sc delete MyService



