c# - 手动添加参数?

标签 c# asp.net-core-mvc swashbuckle

Aspnet.Core 上的 Swashbuckle 通常从方法签名中读取所需的参数,例如

[HttpGet]
[Route("/api/datasets/{id}")]
[SwaggerOperation("DatasetsIdGet")]
[SwaggerResponse(200, type: typeof(DataSet))]
public IActionResult DatasetsIdGet([FromRoute]string id)
{
    string exampleJson = null;

    var example = exampleJson != null ? JsonConvert.DeserializeObject<DataSet>(exampleJson) : default(DataSet);
    return new ObjectResult(example);
}

ID 来自路由,可通过 Swagger-UI 和生成的规范获得。

不幸的是,我必须上传一些非常大的文件,并且想禁用方法的表单绑定(bind)

public async Task<IActionResult> Upload()
{
// drain fields manually. see https://learn.microsoft.com/en-us/aspnet/core/mvc/models/file-uploads
// assume that there is the field bigupload.
}

使用 Swagger-Editor 我可以很容易地描述这个场景——但是我如何才能让 Swashbuckle 相信这个方法有 bigupload 作为必填字段?

编辑

这是我基于 swashbuckle github 中的一个线程的解决方案

public class ImportFileParamType : IOperationFilter
{

    /// <summary>
    /// Adds formData Attributes to the Swagger Documentation.
    /// Must be registered in Startup.cs
    /// </summary>
    /// <param name="operation"></param>
    /// <param name="context"></param>
    public void Apply(Operation operation, OperationFilterContext context)
    {
        Console.WriteLine("ok");

        var attributes = context.ApiDescription.ActionAttributes()
        .OfType<SwaggerFormParameter>();

        foreach (var attribute in attributes)
        {
            if (operation.Parameters == null)
            {
                operation.Parameters = new List<IParameter>();
            }

            if (operation.Consumes.Count == 0)
            {
                operation.Consumes.Add("multipart/form-data");
            }

            var collectionFormat = attribute.CollectionFormat == CollectionFormat.None ? "" : attribute.CollectionFormat.ToString();

            operation.Parameters.Add(new NonBodyParameter()
            {
                Name = attribute.Name,
                Description = attribute.Description,
                In = "formData",
                Required = attribute.IsRequired,
                Type = attribute.Type,
                CollectionFormat = collectionFormat
            });
        }

        Console.WriteLine("ok");
    }
}

public enum CollectionFormat
{
    csv,
    ssv,
    tsv,
    pipes,
    None
}

/// <summary>
/// Adds pure FormData Objects to a Swagger Description. Useful if you cannot do Modelbinding because the uploaded Data is too large.
/// Set the type to "file" if you want files. Otherwise all supported primitve swagger-types should be ok.
/// </summary>
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
public sealed class SwaggerFormParameter : Attribute
{
    public string Name { get; private set; }
    public string Type { get; private set; }
    public string Description { get; set; }
    public bool IsRequired { get; set; }

    public CollectionFormat CollectionFormat { get; set; }

    public SwaggerFormParameter(string name, string type)
    {
        Name = name;
        Type = type;
    }
}

最佳答案

您可以使用 IOperationFilter 来做到这一点

    public class AddRequiredParameters : IOperationFilter
    {
        public void Apply(Operation operation, SchemaRegistry s, ApiDescription a)
        {
            if (operation.operationId == "ControllerName_Upload")
            {
                if (operation.parameters == null)
                    operation.parameters = new List<Parameter>();
                operation.parameters.Add(
                    new Parameter
                    {
                        name = "bigupload",
                        @in = "body",
                        @default = "123",
                        type = "string",
                        description = "bla bla",
                        required = true
                    }
                );                    
            }
        }
    }

这是一个完整的例子:SwaggerConfig.cs#L505

关于c# - 手动添加参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47596216/

相关文章:

c# - 如何创建使用表格作为数据源的折线图?

c# - 从同一个表单同时保存多行 - dotnet core

asp.net-core - 使用 Asp.net core 的 Swashbuckle 如何将模型添加到生成的模型列表中?

asp.net-core - Swashbuckle.AspNetCore 所需的查询字符串参数

c# - 在 Web API 的 Swagger 文档中支持基于 token 的身份验证

c# - 网页访问问题

c# - 如何在 C# 上从 VLC 播放 RTSP

c# - 按出现次数对字符串行进行排序

asp.net-core - ASPNetCore MVC 路由让服务器处理特定路由

asp.net-core - .NET Core SDK 安装程序无法在 Windows 2012 R2 Standard 上安装