我正在使用 nswag 来生成 swagger。但是 openapi json 文件仅在内存中,您只能通过启动应用程序并导航到链接 swagger/v1/swagger.json 来访问它。
我希望在每次构建后生成 json 文件并物理保存在项目中。 我应该如何实现这个目标?
在项目根目录中创建一个
nswag.json
配置文件,并在其中指定,例如"output": "swagger.json"
。
请参阅此处 nswag.json
的文档:https://github.com/RicoSuter/NSwag/wiki/NSwag-Configuration-Document
然后将类似的内容添加到您的
.csproj
文件中,使其在构建项目时运行:
<Target Name="NSwag" AfterTargets="PostBuildEvent" Condition=" '$(Configuration)' == 'Debug' ">
<Exec WorkingDirectory="$(ProjectDir)" EnvironmentVariables="ASPNETCORE_ENVIRONMENT=Development" Command="$(NSwagExe_Net60) run nswag.json /variables:Configuration=$(Configuration)" />
</Target>
请参阅此处的文档:https://github.com/RicoSuter/NSwag/wiki/NSwag.MSBuild
我创建了一个托管服务,它执行我的自定义方法来生成 api 文件并将其保存在项目文件夹中
public static async Task GenerateOpenApiDoc(IServiceProvider services, string contentRootPath)
{
#if DEBUG
int oldvalue = Interlocked.CompareExchange(ref _executed, 1, 0);
if (oldvalue == 1)
{
return;
}
string GetProjectDir()
{
string contentRoot = contentRootPath;
string assemblyName = Assembly.GetEntryAssembly().GetName().Name;
string projName = $"{assemblyName}.csproj";
while (true)
{
if (string.IsNullOrEmpty(contentRoot))
{
return null;
}
if (!Directory.Exists(contentRoot))
{
return null;
}
string projPath = Path.Combine(contentRoot, projName);
if (File.Exists(projPath))
{
return Path.GetDirectoryName(projPath);
}
contentRoot = Directory.GetParent(contentRoot)?.FullName;
}
}
await Task.Run(async () =>
{
using (var serviceScope = services.GetService<IServiceScopeFactory>()!.CreateScope())
{
IServiceProvider serviceProvider = serviceScope.ServiceProvider;
var options = serviceProvider.GetService<IOptions<SwaggerOptions>>();
string documentName = options.Value.Name;
var documentProvider = serviceProvider.GetService<NSwag.Generation.IOpenApiDocumentGenerator>() ?? throw new InvalidOperationException("The NSwag DI services are not registered: Call AddSwaggerDocument() in ConfigureServices().");
NSwag.OpenApiDocument apidoc = await documentProvider.GenerateAsync(documentName);
string spec = apidoc.ToJson();
string path = GetProjectDir();
string assemblyName = Assembly.GetEntryAssembly().GetName().Name;
if (string.IsNullOrEmpty(path))
{
throw new InvalidOperationException($"Не удалось получить путь к директории проекта для {assemblyName}");
}
string filePath = Path.Combine(path, $"{assemblyName}.json");
File.WriteAllText(filePath, spec);
}
});
#else
await Task.CompletedTask;
#endif
}