Swashbuckle.AspNetCore.Cli不能与appsettings.json一起工作



似乎我不能得到Swashbuckle.AspNetCore.Cli工作与我的。net Core 3.1项目。我已经安装了Cli使用这些指令和构建项目工作良好。但每当我试图创造出狂妄自大的时候。Json,它给了我未处理的异常相关的应用设置。找不到Json变量。似乎使用Cli工具运行程序集不会加载我的设置。以前有人遇到过这个问题吗?

Unhandled exception. System.NullReferenceException: Object reference not set to an instance of an object.

我在。net 6和Swashbuckle 6.2.3中遇到了这个问题。我必须检查条目程序集,正如评论中建议的那样:

AppConfig? configuration = null;
var builder = WebApplication.CreateBuilder(args);
if (Assembly.GetEntryAssembly()?.GetName().Name != "dotnet-swagger")
{
// Had only this line previously
builder.Host.ConfigureAppConfiguration(config => configuration = config.Build().Get<AppConfig>());
}
else
{
configuration = new AppConfig { /* Configure manually for Swagger's use */ };
}

如果目的是在代码外部生成,并且各种问题阻止它正确加载,则可以使用应用程序的最简单版本创建另一个入口点,以提供swagger生成器所需的内容,如下所示:

public static class SwaggerGen
{
public static bool EntryPointForSwaggerGenerationApplication(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
if (Assembly.GetEntryAssembly()?.GetName().Name == "dotnet-swagger")
{
// Add services to the container.
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var appForGen = builder.Build();
appForGen.UseSwagger();
appForGen.UseSwaggerUI(options =>
{
options.SwaggerEndpoint("/swagger/v1/swagger.json", Names.ApplicationName);
});
appForGen.Run();
return true;
}
return false;
}
}

然后你的程序开始看起来像这样:

if (SwaggerGen.EntryPointForSwaggerGenerationApplication(args))
return;

这将允许swagger生成从dotnet swagger tofile运行,并且只进入这个允许它访问所需内容的小应用程序。

最新更新