Unable to resolve service for type 'Swashbuckle.AspNetCore.Swagger.ISwaggerProvider'

.net core项目集成Swagger后,可以在本地运行查看接口,但是部署到测试机的IIS之后,无法使用,导致应用程序启动不起来,一直报错:

ERROR|Microsoft.AspNetCore.Server.IIS.Core.IISHttpServer|Connection ID "16212958664439370925", Request ID "800014ae-0001-e100-b63f-84710c7967bb": An unhandled exception was thrown by the application. System.InvalidOperationException: Unable to resolve service for type 'Swashbuckle.AspNetCore.Swagger.ISwaggerProvider' while attempting to Invoke middleware 'Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware'.
   at Microsoft.AspNetCore.Builder.UseMiddlewareExtensions.GetService(IServiceProvider sp, Type type, Type middleware)
   at lambda_method(Closure , Object , HttpContext , IServiceProvider )
   at Microsoft.AspNetCore.Builder.UseMiddlewareExtensions.<>c__DisplayClass4_1.<UseMiddleware>b__2(HttpContext context)
   at Microsoft.AspNetCore.Localization.RequestLocalizationMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
   at Abp.AspNetCore.Security.AbpSecurityHeadersMiddleware.Invoke(HttpContext httpContext)
   at Microsoft.AspNetCore.Server.IIS.Core.IISHttpContextOfT`1.ProcessRequestAsync()

即:Unable to resolve service for type 'Swashbuckle.AspNetCore.Swagger.ISwaggerProvider' while attempting to Invoke middleware 'Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware'.

如果不注册Swagger,应用程序即可正常显示,但是为了让前端人员查看接口文档,还是需要进行配置Swagger,那如何解决?

原因:

IIS未配置全局的ASPNETCORE_ENVIRONMENT值,比如Development、Production环境变量。

解决方案一:

1、C:\Windows\System32\inetsrv\config\applicationHost.config  到部署的电脑,打开这个文件。

2、找到你部署的站点名称以及节点,比如: <add name="TC.Host" managedRuntimeVersion="" managedPipelineMode="Integrated">

3、添加节点,指明环境:

<environmentVariables>
         <add name="ASPNETCORE_ENVIRONMENT" value="Development" />
 </environmentVariables>

4、重启站点即可。

解决方案二:

通过配置编辑器,进行添加环境变量,可以参考如下:

参考资料:https://stackoverflow.com/questions/31049152/publish-to-iis-setting-environment-variable

发布了209 篇原创文章 · 获赞 370 · 访问量 1954万+

猜你喜欢

转载自blog.csdn.net/lilinoscar/article/details/98357000