ASP.NET Core网站更新DLL文件时报错文件被占用

在开发ASP.NET Core项目过程中,又踩了一个坑。事情是这样的,当使用Jenkins自动部署.Net Core程序时,Jenkins报错,XXX.Dll正在使用,无法删除。于是我连上服务器,找到该Dll手动删除,报错

操作无法完成,因为文件已在dotnet中打开

打开任务管理器,杀掉dotnet.exe进程后,Dll文件就被释放了。

又复现了几次后发现,一旦有用户访问了ASP.NET Core项目网址,后台就会生成一个dotnet.exe进程,该进程会占用程序相关的DLL文件,导致如果想要在生产环境替换DLL文件时,必须先停站。如果不停站,只是杀掉dotnet.exe进程的话,如果此时用户还在不停地刷新页面,会导致再次启动dotnet.exe进程,DLL文件无法得到更新。那有没有办法既不停站,又可以更新DLL文件呢?

答案是可以的。AspNetCoreModule模块支持程序离线模式,什么意思?将一个叫做app_offline.htm的html文件复制到ASP.NET Core网站根目录下,此时用户访问项目网址时只会看到离线页面的内容,不会访问到项目主页。所以,我们只需要在app_offline.htm离线页面中写到网站更新中,一会儿恢复的内容,通知用户网站正在更新,然后在服务器上杀掉dotnet.exe进程,更新DLL,最后删掉app_offline.htm文件即可。

虽然比起ASP.NET项目繁琐了一点,必须杀掉进程后才能替换文件,但是好歹还能控制用户流量的入口,用户体验不会太差。app_offline.htm的内容可以自己修改,比如

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >

<head>

<title>Site Under Construction</title>

</head>

<body>

<h1>Under Construction</h1>



<h2>Gone to Florida for the sun...</h2>



<!--

Adding additional hidden content so that IE Friendly Errors don't prevent

this message from displaying (note: it will show a "friendly" 404

error if the content isn't of a certain size).



<h2>Gone to Florida for the sun...</h2>


<h2>Gone to Florida for the sun...</h2>

<h2>Gone to Florida for the sun...</h2>

<h2>Gone to Florida for the sun...</h2>

<h2>Gone to Florida for the sun...</h2>

<h2>Gone to Florida for the sun...</h2>

<h2>Gone to Florida for the sun...</h2>

<h2>Gone to Florida for the sun...</h2>

<h2>Gone to Florida for the sun...</h2>

<h2>Gone to Florida for the sun...</h2>

<h2>Gone to Florida for the sun...</h2>

<h2>Gone to Florida for the sun...</h2>

<h2>Gone to Florida for the sun...</h2>

-->

</body>

</html>
avatar

chilihotpot

You Are The JavaScript In My HTML