簡體   English   中英

自定義 Swagger UI 方法參數占位符

[英]Custom Swagger UI method parameter placeholder

是否可以將方法參數的背景占位符文本(例如fromDate (參見圖片)更改為其他內容 lile yyyy-MM-dd

在此處輸入圖像描述

到目前為止,我已經嘗試將以下內容添加到我的端點而沒有實現我真正想要的。

.WithOpenApi(operation =>
{
    operation.Summary = "Summary text";
    var parameter = operation.Parameters[0];
    parameter.Example = new OpenApiString("example text");
    return operation;
});

首先你應該添加SwaggerDefaultValues操作過濾器

    /// <summary>
    /// Represents the Swagger/Swashbuckle operation filter used to document the implicit API version parameter.
    /// </summary>
    /// <remarks>This <see cref="IOperationFilter"/> is only required due to bugs in the <see cref="SwaggerGenerator"/>.
    /// Once they are fixed and published, this class can be removed.</remarks>
    public class SwaggerDefaultValues : IOperationFilter
    {
        /// <summary>
        /// Applies the filter to the specified operation using the given context.
        /// </summary>
        /// <param name="operation">The operation to apply the filter to.</param>
        /// <param name="context">The current operation filter context.</param>
        public void Apply( OpenApiOperation operation, OperationFilterContext context )
        {
            var apiDescription = context.ApiDescription;

            // REF: https://github.com/domaindrivendev/Swashbuckle.AspNetCore/issues/1752#issue-663991077
            foreach ( var responseType in context.ApiDescription.SupportedResponseTypes )
            {
                // REF: https://github.com/domaindrivendev/Swashbuckle.AspNetCore/blob/b7cf75e7905050305b115dd96640ddd6e74c7ac9/src/Swashbuckle.AspNetCore.SwaggerGen/SwaggerGenerator/SwaggerGenerator.cs#L383-L387
                var responseKey = responseType.IsDefaultResponse ? "default" : responseType.StatusCode.ToString();
                var response = operation.Responses[responseKey];

                foreach ( var contentType in response.Content.Keys )
                {
                    if ( !responseType.ApiResponseFormats.Any( x => x.MediaType == contentType ) )
                    {
                        response.Content.Remove( contentType );
                    }
                }
            }

            if ( operation.Parameters == null )
            {
                return;
            }

            // REF: https://github.com/domaindrivendev/Swashbuckle.AspNetCore/issues/412
            // REF: https://github.com/domaindrivendev/Swashbuckle.AspNetCore/pull/413
            foreach ( var parameter in operation.Parameters )
            {
                var description = apiDescription.ParameterDescriptions.First( p => p.Name == parameter.Name );

                if ( parameter.Description == null )
                {
                    parameter.Description = description.ModelMetadata?.Description;
                }

                if ( parameter.Schema.Default == null && description.DefaultValue != null )
                {
                    // REF: https://github.com/Microsoft/aspnet-api-versioning/issues/429#issuecomment-605402330
                    var json = JsonSerializer.Serialize( description.DefaultValue, description.ModelMetadata.ModelType );
                    parameter.Schema.Default = OpenApiAnyFactory.CreateFromJson( json );
                }

                parameter.Required |= description.IsRequired;
            }
        }
    }

之后你應該用 Swagger 注冊它

builder.Services.AddSwaggerGen(options =>
{
    // add a custom operation filter which sets default values
    options.OperationFilter<SwaggerDefaultValues>();
    
    var fileName = typeof( Program ).Assembly.GetName().Name + ".xml";
    var filePath = Path.Combine( AppContext.BaseDirectory, fileName );

    // integrate xml comments
    options.IncludeXmlComments( filePath );
});

請務必啟用要發布的文檔文件,所以用這個編輯相應的csproj

 <PropertyGroup>
  
  <GenerateDocumentationFile>true</GenerateDocumentationFile>
 </PropertyGroup>

使用此設置,此控制器將如下所示

    /// <summary>
    /// Example here is GetWithBodyMethodParameters
    /// </summary>
    /// <param name="id" example="5">One of IDs</param>
    /// <param name="text" example="something">Some text used to filter</param>
    /// <returns></returns>
    [HttpGet("/with-body-method-parameters/{id}")]
    public IActionResult GetWithBodyMethodParameters(int id, [FromBody] string text) => Ok();

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM