简体   繁体   English

为 Swagger 路径参数添加默认值

[英]Add default value to Swagger path parameters

I have made a WebAPI in .NET CORE 6.我在 .NET CORE 6 中创建了一个 WebAPI。

I have a controller class like this:我有一个这样的控制器类:

    [ApiController]
    [Route("{culture:culture}/[controller]")]
    [SwaggerDefaultValue("culture", "en-US")]
    [Produces("application/json")]
    public class AccountsController : BaseController
    {
         ...
    }

As you can see I defined a parameter in the route like this {culture:culture} .如您所见,我在{culture:culture}这样的路线中定义了一个参数。

I would like to have a default value for this parameter in my Swagger.我想在我的 Swagger 中为这个参数设置一个默认值。

I defined an attribute class like this:我定义了一个这样的属性类:

    [AttributeUsage(AttributeTargets.Class )]
    public class SwaggerDefaultValueAttribute:Attribute
    {
        public string Name { get; set; }
        public string Value { get; set; }

        public SwaggerDefaultValueAttribute(string name, string value)
        {
            Name = name;
            Value = value;
        }
    }

And a filter class like this:还有一个像这样的过滤器类:

    public class SwaggerDefaultValueFilter : IOperationFilter
    {
        public void Apply(OpenApiOperation operation, OperationFilterContext context)
        {
           // needs some code
        }
    }

And added the filter to my Swagger service too.并将过滤器也添加到我的 Swagger 服务中。

options.OperationFilter<SwaggerDefaultValueFilter>();

However, the problem is most of the code samples that I found are related to the old versions of Swagger and most of their methods are deprecated (like this one ).但是,问题是我发现的大多数代码示例都与旧版本的 Swagger 相关,并且它们的大多数方法都已被弃用(例如这个)。

The question is, how can I modify this SwaggerDefaultValueFilter class to show a default value in my path parameter:问题是,如何修改此 SwaggerDefaultValueFilter 类以在我的路径参数中显示默认值:

在此处输入图像描述

FYI: I am using <PackageReference Include="Swashbuckle.AspNetCore.SwaggerUI" Version="6.2.3" /> .仅供参考:我正在使用<PackageReference Include="Swashbuckle.AspNetCore.SwaggerUI" Version="6.2.3" />

I found this sample too, however, it does not set the default values of the path parameters, it seems it works for model attributes.我也找到了这个示例,但是,它没有设置路径参数的默认值,它似乎适用于模型属性。

Not Swashbuckle.AspNetCore but this might send you on the right path:不是Swashbuckle.AspNetCore但这可能会让你走上正确的道路:

Controller:控制器:
https://github.com/heldersepu/Swagger-Net-Test/blob/master/Swagger_Test/Controllers/CompanyController.cs#L35-L39 https://github.com/heldersepu/Swagger-Net-Test/blob/master/Swagger_Test/Controllers/CompanyController.cs#L35-L39

        [Route("Get2")]
        public Company Get2([FromUri] Company c)
        {
            return c;
        }

Model:模型:
https://github.com/heldersepu/Swagger-Net-Test/blob/master/Swagger_Test/Models/Company.cs https://github.com/heldersepu/Swagger-Net-Test/blob/master/Swagger_Test/Models/Company.cs

    public class Company
    {
        /// <summary>The Unique Company ID</summary>
        /// <example>123</example>
        [Required]
        [DefaultValue(456)]
        public int Id { get; set; }

        [Required]
        [DefaultValue(null)]
        public int? MyId { get; set; }

        /// <summary>The Company Name</summary>
        /// <example>Acme co</example>
        [DefaultValue("My Company")]
        public string Name { get; set; }

Live code:实时代码:
http://swagger-net-test.azurewebsites.net/swagger/ui/index?filter=Company#/Company/Company_Get2 http://swagger-net-test.azurewebsites.net/swagger/ui/index?filter=Company#/Company/Company_Get2

To assign the default value for the parameter, you can do something like this,要为参数分配默认值,您可以执行以下操作,

internal static class OperationFilterContextExtensions
{
    public static IEnumerable<T> GetControllerAndActionAttributes<T>(this OperationFilterContext context) where T : Attribute
    {
        var controllerAttributes = context.MethodInfo.DeclaringType.GetTypeInfo().GetCustomAttributes<T>();
        var actionAttributes = context.MethodInfo.GetCustomAttributes<T>();

        var result = new List<T>(controllerAttributes);
        result.AddRange(actionAttributes);
        return result;
    }
}

public class SwaggerDefaultValueFilter : IOperationFilter
{
    public void Apply(OpenApiOperation operation, OperationFilterContext context)
    {

        var defaultAttributes = context.GetControllerAndActionAttributes<SwaggerDefaultValueAttribute>();

        if (defaultAttributes.Any())
        {
            foreach (var defaultAttribute in defaultAttributes)
            {
                var parameter = operation.Parameters.FirstOrDefault(d => d.Name == defaultAttribute.Name);
                if (parameter != null)
                {
                    version.Schema.Default = new OpenApiString(defaultAttribute.Value);
                }
            }
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM