4

使用任务计划开机启动ASP.NET Core应用程序 - 深蓝医生

 7 months ago
source link: https://www.cnblogs.com/bluedoctor/p/17714151.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

使用任务计划开机启动ASP.NET Core应用程序

ASP.NET Core应用程序现在是一个控制台应用程序,在Windows上直接双击启动,但如果想让开发完成的ASP.NET Core应用程序开机启动,可以将ASP.NET Core应用程序修改成Windows服务运行,但这需要额外添加代码,也可以使用IIS来托管ASP.NET Core应用程序,但可能需要安装一些支持IIS的组件,第三个方式就是用Windows任务计划来设置开机启动。

但是,当一个ASP.NET Core应用程序直接使用Windows任务计划启动的时候,ASP.NET Core应用程序无法正确读取到应用程序的配置文件从而导致程序运行出错,问题的原因在于任务计划执行的当前工作目录不是ASP.NET Core应用程序所在目录,而直接在ASP.NET Core应用程序里面设置当前工作目录是无效的,应用程序启动之前配置文件的目录可能就已经确定了,例如下面的代码:

var app = builder.Build();
app.UseStaticFiles();
//其它代码略...
string basePath1 = AppContext.BaseDirectory;
Environment.CurrentDirectory = basePath1;
Console.WriteLine("Set Current Work Directory:{0}", Directory.GetCurrentDirectory());
app.Run();

上面在ASP.NET Core应用程序里面设置当前工作目录是无效的,代码环境为 ASP.NET Core WebAPI,.NET 6.0

解决这个问题是使用另外一个应用程序修改当前环境工作目录为ASP.NET Core应用程序所在目录即可,假设这个应用程序名字是Start,用任务计划启动Start.exe,而ASP.NET Core应用程序路径作为Start的命令行参数即可,完整代码如下:

namespace Start
{
    internal class Program
    {
        static void Main(string[] args)
        {
            string basePath1 = AppContext.BaseDirectory;
            Environment.CurrentDirectory = basePath1;

            Console.WriteLine("Set Current Work Directory:{0}", Directory.GetCurrentDirectory());
            if (args.Length == 0)
            { 
                Console.WriteLine("no command line args,example:\r\n Start.exe exe_file_path");
                System.Threading.Thread.Sleep(3000);
                return;
            }
            string path= args[0];
            if (System.IO.File.Exists(path))
            {
                string? path2= Path.GetDirectoryName(path);
                if (!string.IsNullOrEmpty(path2))
                {
                    Environment.CurrentDirectory = path2;
                    Console.WriteLine("Set Current Work Directory:{0}", Directory.GetCurrentDirectory());
                }
                Console.WriteLine("start programe : {0}", path);
                System.Diagnostics.Process.Start(path);
            }
            else
            {
                Console.WriteLine("file not exists:{0}", path);
            }
            System.Threading.Thread.Sleep(3000);
        }
    }
}

之后,在任务计划里面如下图进行配置,即可顺利的在系统启动就运行ASP.NET Core应用程序了。

114517-20230919111014417-222077085.png

图1:添加一个系统启动执行任务的任务计划

114517-20230919111101772-728824127.png

图2:任务计划启动start.exe,然后启动ASP.NET Core应用程序。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK