swagger - Swashbuckle ASP.NET Core 消费 application/x-www-form-urlencoded

标签 swagger swashbuckle

我有一个使用 application/x-www-form-urlencoded 的操作:

[HttpPost("~/connect/token"), Consumes("application/x-www-form-urlencoded")]
public async Task<IActionResult> Exchange([FromBody]OpenIdConnectRequest request)
{
   ..
}

但是 Swashbuckle 为 Consumes property 生成空数组.如果我把它改成 application/json , 消费数组正确生成。

是否与 application/x-www-form-urlencoded 相关的错误或者我需要额外配置 Swashbuckle 以支持这种应用程序类型?

最佳答案

'consumes' 不适合 Swashbuckle 的开箱即用,需要自定义扩展,如 @domaindrivendev's GitHub project 的这一部分中的扩展。

共有三个步骤:

  • 创建参数属性
  • 创建扩展
  • 向 Swashbuckle 添加指令以处理新扩展
  • 为 Controller 方法中的参数添加属性

  • 我将在 my fork of the repo 中添加更多说明,但这里是代码:

    1.FromFormDataBodyAttribute.cs
    using System;
    using System.Collections.Generic;
    using System.Net.Http.Formatting;
    using System.Web.Http;
    using System.Web.Http.Controllers;
    using System.Web.Http.Validation;
    
    /// <summary>
    /// FromFormDataBody Attribute
    /// This attribute is used on action parameters to indicate
    /// they come only from the content body of the incoming HttpRequestMessage.
    /// </summary>
    [AttributeUsage(AttributeTargets.Parameter, Inherited = true, AllowMultiple = false)]
    public sealed class FromFormDataBodyAttribute : ParameterBindingAttribute
    {
        /// <summary>
        /// GetBinding
        /// </summary>
        /// <param name="parameter">HttpParameterDescriptor</param>
        /// <returns>HttpParameterBinding</returns>
        public override HttpParameterBinding GetBinding(HttpParameterDescriptor parameter)
        {
            if (parameter == null)
                throw new ArgumentNullException("parameter");
    
            IEnumerable<MediaTypeFormatter> formatters = parameter.Configuration.Formatters;
            IBodyModelValidator validator = parameter.Configuration.Services.GetBodyModelValidator();
    
            return parameter.BindWithFormatter(formatters, validator);
        }
    }
    

    2 AddUrlFormDataParams.cs
    using Swashbuckle.Swagger;
    using System.Linq;
    using System.Web.Http.Description;
    
    /// <summary>
    /// Add UrlEncoded form data support for Controller Actions that have FromFormDataBody attribute in a parameter
    /// usage: c.OperationFilter<AddUrlFormDataParams>();
    /// </summary>
    public class AddUrlFormDataParams : IOperationFilter
    {
        public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
        {
            var fromBodyAttributes = apiDescription.ActionDescriptor.GetParameters()
                .Where(param => param.GetCustomAttributes<FromFormDataBodyAttribute>().Any())
            .ToArray();
    
            if (fromBodyAttributes.Any())
                operation.consumes.Add("application/x-www-form-urlencoded");
    
            foreach (var headerParam in fromBodyAttributes)
            {
                if (operation.parameters != null)
                {
                    // Select the capitalized parameter names
                    var parameter = operation.parameters.Where(p => p.name == headerParam.ParameterName).FirstOrDefault();
                    if (parameter != null)
                    {
                        parameter.@in = "formData";//NB. ONLY for this 'complex' object example, as it will be passed as body JSON.
    //TODO add logic to change to "query" for string/int etc. as they are passed via query string.
                    }
                }
            }
        }
    }
    

    3 更新 Swagger.config
     //Add UrlEncoded form data support for Controller Actions that have FromBody attribute in a parameter
    c.OperationFilter<AddUrlFormDataParams>();
    

    4.在Controller方法中给参数添加一个属性
    [FromFormDataBody]OpenIdConnectRequest request
    

    关于swagger - Swashbuckle ASP.NET Core 消费 application/x-www-form-urlencoded,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41880072/

    相关文章:

    php - 从open api导入数据并使用循环结合mysql循环

    file - 如何在 Swagger-UI 中打开本地文件

    c# - 如何手动添加到 swagger 的 schemas 部分?

    java - OAuth 2.0 - 第一步细节,有人可以澄清吗?

    azure - 从 swagger 文件生成 Azure API 应用程序客户端时出现 NotSupportedException

    asp.net-core - AspNetCore 自定义/显式 Swagger OperationId

    c# - 如何从 swagger.json 中删除反引号

    javascript - 从 JSDoc 生成 Swagger YAML?

    c# - Swagger - 隐藏 api 版本参数

    swagger - 过渡到 Swashbuckle 5.0