2024-01-26 08:44:48 +03:00
|
|
|
|
using Microsoft.AspNetCore.Mvc.ApiExplorer;
|
|
|
|
|
using Microsoft.AspNetCore.Mvc.ModelBinding;
|
|
|
|
|
using Microsoft.OpenApi.Models;
|
|
|
|
|
using Swashbuckle.AspNetCore.SwaggerGen;
|
|
|
|
|
using System;
|
|
|
|
|
using System.Linq;
|
|
|
|
|
using System.Text.Json;
|
|
|
|
|
|
2024-01-28 06:29:47 +03:00
|
|
|
|
namespace Mirea.Api.Endpoint.Configuration;
|
2024-01-26 08:44:48 +03:00
|
|
|
|
|
|
|
|
|
public class SwaggerDefaultValues : IOperationFilter
|
|
|
|
|
{
|
|
|
|
|
public void Apply(OpenApiOperation operation, OperationFilterContext context)
|
|
|
|
|
{
|
|
|
|
|
var apiDescription = context.ApiDescription;
|
|
|
|
|
operation.Deprecated |= apiDescription.IsDeprecated();
|
|
|
|
|
|
|
|
|
|
foreach (var responseType in context.ApiDescription.SupportedResponseTypes)
|
|
|
|
|
{
|
|
|
|
|
var responseKey = responseType.IsDefaultResponse ? "default" : responseType.StatusCode.ToString();
|
|
|
|
|
var response = operation.Responses[responseKey];
|
|
|
|
|
|
|
|
|
|
foreach (var contentType in response.Content.Keys)
|
|
|
|
|
{
|
|
|
|
|
if (responseType.ApiResponseFormats.All(x => x.MediaType != contentType))
|
|
|
|
|
{
|
|
|
|
|
response.Content.Remove(contentType);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (operation.Parameters == null)
|
|
|
|
|
{
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
foreach (var parameter in operation.Parameters)
|
|
|
|
|
{
|
|
|
|
|
var description = apiDescription.ParameterDescriptions.First(p => p.Name == parameter.Name);
|
|
|
|
|
|
2024-01-28 06:29:47 +03:00
|
|
|
|
parameter.Description ??= description.ModelMetadata.Description;
|
2024-01-26 08:44:48 +03:00
|
|
|
|
|
|
|
|
|
if (parameter.Schema.Default == null &&
|
|
|
|
|
description.DefaultValue != null &&
|
|
|
|
|
description.DefaultValue is not DBNull &&
|
|
|
|
|
description.ModelMetadata is ModelMetadata modelMetadata)
|
|
|
|
|
{
|
|
|
|
|
var json = JsonSerializer.Serialize(description.DefaultValue, modelMetadata.ModelType);
|
|
|
|
|
parameter.Schema.Default = OpenApiAnyFactory.CreateFromJson(json);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
parameter.Required |= description.IsRequired;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|