如何在代码c# .net 5中获得当前使用的openapi版本



如何获取" openapi ";版本通过代码把它放到自己的控制器响应?

当您打印openapi生成的JSON时,它以

开头
{
"openapi": "3.0.1",
"info": {
...
}

,我想要得到值&;3.0.1&;作为字符串。是否有一种方法可以像依赖注入或类似的东西一样将其访问到控制器中?

的例子:

[ApiController]
[Route("api/my-app/openapi-version")]
public class OpenApiVersionController: ControllerBase
private IOptions<Configuration> Configuration;
// Use DI to access to my own configuration
public OpenApiVersionController(IOptions<Configuration> configuration)
{
this.Configuration = configuration;
}
[HttpGet, Route("")]
public ActionResult<OpenApiVersion> GetOpenApiVersion()
{
string version = // What should I write here ?
Ok(new OpenApiVersion(version));
}
}

我使用。net和Swashbuckle

您可以通过这种方式获得请求的版本

HttpContext.GetRequestedApiVersion()

有点旧的线程,但我终于找到了一个解决方案(不那么漂亮,但它的工作):

[ApiController] [Route("api/my-app/openapi-version")] 
public class OpenApiVersionController : ControllerBase 
{
private IOptions<Configuration> Configuration;
// Use DI to access to my own configuration
public OpenApiVersionController(IOptions<Configuration> configuration)
{
this.Configuration = configuration;
}
[HttpGet, Route("")]
public ActionResult<OpenApiVersion> GetOpenApiVersion()
{
Assembly assembly = Assembly.GetExecutingAssembly();
string openApiVersion = $"Unable to get version. Default version: 3.0.1";
using (HttpClient client = new HttpClient())
{
string uri = $"{HttpContext.Request.Scheme}://{HttpContext.Request.Host}";
client.BaseAddress = new Uri(uri);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.GetAsync("/api/v1/xxxxx.openapi.json");  // same as define in c.SwaggerEndpoint("/api/v1/xxxxx.openapi.json", ...) in Startup.cs
if (response.IsSuccessStatusCode)
{
string json = await response.Content.ReadAsStringAsync();
foreach (string s in json.Split(","))
{
if (s.Contains("openapi")) // could certainly be improved with regex !
{
try
{
openApiVersion = s.Split(":")[1]?.Replace(""", "")?.Trim();
}
catch
{
// parsing error, default openApiversion is returned
}
}
}
}
}
OpenApiVersion version = new OpenApiVersion // model for endpoint return
{
appVersion = FileVersionInfo.GetVersionInfo(assembly.Location).FileVersion,
dotNetVersion = Environment.Version.ToString(),
openApiVersion = openApiVersion
};
Ok(version);
}
}

想法是读取生成的JSON,因为它包含OPENAPI版本

最新更新