我想访问swagger。Json文件,并将其反序列化并存储到缓存中。
我正在IHostedService
中进行异步调用。
public class InitializeCacheService : IHostedService
{
private IMemoryCache _cache;
public static readonly string swaggerJson = "swagger.json";
private readonly HttpClient _httpClient;
private readonly IServiceProvider _serviceProvider;
public InitializeCacheService(IMemoryCache cache, HttpClient client, IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
_httpClient = client;
_cache = cache;
}
public async Task StartAsync(CancellationToken cancellationToken)
{
if (!_cache.TryGetValue(swaggerJson, out SwaggerDocumentCache cacheEntry))
{
_httpClient.BaseAddress = new Uri("https://localhost:44397");
var response = await _httpClient.GetAsync("swagger/v1/swagger.json");
response.EnsureSuccessStatusCode();
using var responseStream = await response.Content.ReadAsStreamAsync();
cacheEntry = await JsonSerializer.DeserializeAsync
<SwaggerDocumentCache>(responseStream);
var cacheEntryOptions = new MemoryCacheEntryOptions()
.SetSlidingExpiration(TimeSpan.FromSeconds(3));
_cache.Set(swaggerJson, cacheEntry, cacheEntryOptions);
}
}
public Task StopAsync(CancellationToken cancellationToken)
{
return Task.CompletedTask;
}
}
但是应用程序一直在旋转,并且它正在超时var response = await _httpClient.GetAsync("swagger/v1/swagger.json");
给出的错误是:
IOException: Unable to read data from transport connection:由于线程退出或应用程序请求,I/O操作已经中止。
我在这里错过了什么?访问swagger.json
构建自定义API游乐场应用程序的正确方法是什么?
SwaggerMiddleware处理服务OpenAPI文档。我们可以使用它作为参考来构建自己的文档。
第一个寄存器SwaggerGenerator
与DI:
// Startup.Configure
services.AddTransient<SwaggerGenerator>();
然后注入到一个类中,这里我使用一个端点来直接服务它:
// Startup.Configure
app.UseEndpoints(e =>
{
// ...
e.MapGet("/openapi.json", context =>
{
// inject SwaggerGenerator
var swaggerGenerator = context.RequestServices.GetRequiredService<SwaggerGenerator>();
// document name is defined in Startup.ConfigureServices method inside the AddSwaggerGen call
var doc = swaggerGenerator.GetSwagger("v1");
// serialize the document as json
using var writer = new StringWriter(CultureInfo.InvariantCulture);
var serializer = new OpenApiJsonWriter(writer);
doc.SerializeAsV3(serializer);
var json = writer.ToString(); // this is the openapi document
// serve it as json
context.Response.ContentType = MediaTypeNames.Application.Json;
return context.Response.WriteAsync(json, new UTF8Encoding(false));
});
});
我认为实际的JSON不一定是有效的端点,这本身可能是一个问题。您是否尝试了在端点路由上没有显式文件名的调用?