大家习惯将服务注册写进Startup中的Configure管道配置,用来在服务启动时进行Consul服务注册,如图:
然后将服务部署在IIS下,部署好之后,点击启动网站,却发现服务并没有注册进Consul,然后我就查其原因:
也就是说,使用IIS托管时,不管是进程内外托管,都会有这个问题,第一个请求时,应用才会运行起来,我用Exceptionless做了实测(进程外托管程序是dotnet),验证后无疑。
解决方案:
(1)使用IIS预加载,来自动触发第一个请求达到服务注册的目的(或每次部署完手动浏览或其他请求模拟器来达到启动IIS工作进程的目的)。
*先打开windows的应用初始化功能,很重要,因为不打开也能配置预加载,只是不会生效,笑哭(WIN10为例)
1、打开“开启和关闭Windows”功能
2、点击internet information services
3、点击“万维网服务”
4、点击“应用程序开发功能”
5、勾选“应用程序初始化”
*IIS的配置(我直接截图)
1.更改网站对应的应用程序池的启动模式
2.网站启用预加载
3.配置预加载请求
注意:预加载解决了注册问题,但是带来了新问题:网站停止时再次触发了预加载,导致consul中注册了一个不可用的服务。
解决:先停网站的应用程序池再停网站可避免这个错误注册的问题。
(2)不使用IIS托管需要注册的服务,换成Windowss Service(可以考虑混合部署,IIS部署一些,Windowss Service部署一些),还有控制台或Windows Docker(选用自己合适的)
asp.net core真是很方便,只需要引入Microsoft.Extensions.Hosting.WindowsServices包(官方文档包引入有误),然后UseWindowsService。发布后使用命令安装成Windows Service就好了
注意:Directory.GetCurrentDirectory()要换成AppContext.BaseDirectory或IHostEnvironment.ContentRootPath,解决宿主Windows Service获取目录问题
哈哈,一个小问题就牵扯出了IIS工作机制和asp.net core的工作机制
文档: