默认的asp.net core应用运行起来后,在windows下会有一个dos窗口,如果不小心关闭后,会导致程序中断运行,并且当服务器重新启动后,程序可能不会自动启动。
为了解决上述问题,在windows下部署时,可以考虑部署到IIS下面或者做为windows服务来运行。下面讲解一下使用windows服务来进行部署时的相关步骤

程序修改

  1. <Project Sdk="Microsoft.NET.Sdk.Web">
  2. <PropertyGroup>
  3. <TargetFramework>netcoreapp2.1</TargetFramework>
  4. <RuntimeIdentifier>win7-x64</RuntimeIdentifier>
  5. <SelfContained>false</SelfContained>
  6. <IsTransformWebConfigDisabled>true</IsTransformWebConfigDisabled>
  7. </PropertyGroup>
  8. </Project>
  • 修改program.cs文件
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)
        {
            // To run the app without the CustomWebHostService change the
            // next line to host.RunAsService();
            host.RunAsService();
        }
        else
        {
            host.Run();
        }
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .ConfigureLogging((hostingContext, logging) =>
            {
                logging.AddEventLog();
            })
            .ConfigureAppConfiguration((context, config) =>
            {
                // Configure the app here.
            })
            .UseStartup<Startup>();
}

增加服务

在项目中增加以下installService.bat文件,并且选择为始终复制,以便发布出来后,可以直接双击此文件来增加服务

echo "本程序将安装捷信达支付中间件为serviceName服务。\n如果安装过程中出现错误,请以管理员的身份来运行"
sc create serviceName binPath= "%cd%\projectName.exe"
sc start serviceName

程序发布出来后,拷贝到目标机器上,运行一下installService.bat文件后,服务将自动创建好并且启动,此时可以在服务中看到此服务和相应的运行状态。
注意:由于增加服务的脚本中使用了当前目录变量,所以要求执行bat文件的时候,是先以管理员身份进入到命令行窗口,并且切换到程序目录后,再运行installService.bat,否则可能会出现服务运行时报找不到指定文件的错误。