.NET Core项目仅可在Visual Studio运行 无法通过终端启动如何解决
解决方案:终端直接运行.NET Core 2.x API项目
报错原因
- 根目录执行
dotnet run报错是因为根目录没有可运行的入口项目文件(.csproj),入口项目存放在API子目录中 - 进入API目录执行命令触发以下报错,是因为该项目配置了Windows服务运行模式,默认逻辑会校验当前环境是否为已安装的服务上下文,非服务场景会直接抛出错误。Visual Studio调试时内置了调试场景的兼容逻辑,所以可以正常启动。
Cannot start service from the command line or a debugger. A Windows Service must first be installed and then started with the ServerExplorer, Windows Services Administrative tool or the NET START command.
具体操作步骤
方案1:修改启动逻辑支持控制台直接运行(推荐,调试用)
修改API项目的Program.cs文件,调整服务启动判断逻辑,支持控制台模式运行,参考代码:
using Microsoft.AspNetCore.Hosting; using System; namespace YourApiNamespace { public class Program { public static void Main(string[] args) { // 判定是否需要以服务模式运行:带--console参数/控制台交互模式下走控制台启动逻辑 var runAsConsole = Console.IsInputRedirected == false || args.Contains("--console"); var host = CreateWebHostBuilder(args).Build(); if (runAsConsole) { host.Run(); } else { host.RunAsService(); } } public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>(); } }
修改完成后,在项目根目录执行以下命令即可直接启动:dotnet run --project ./API/[替换为你的API项目名称].csproj --console
如果已经切换到API目录,直接执行dotnet run --console即可。
方案2:安装为Windows服务运行(适合正式部署)
如果不需要调试,只想正式运行项目,可以先发布项目,再通过系统命令安装为服务:
- 发布项目:在根目录执行
dotnet publish ./API/[替换为你的API项目名称].csproj -c Release -o ./publish - 安装服务:以管理员身份打开终端,执行
sc create 自定义服务名称 binPath= "项目根目录绝对路径/publish/[替换为你的API项目名称].exe" - 启动服务:执行
net start 自定义服务名称
内容的提问来源于stack exchange,提问作者Asghwor
相关产品推荐
相关产品推荐

