Swashbuckle ASP.NET Core使用application/x-www-form-urlencoded

Sib*_*Guy 5 swagger swashbuckle

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

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

但Swashbuckle会为其生成空数组Consumes property.如果我将其更改为application/json,则会正确生成消耗数组.

这是一个与之相关的错误,application/x-www-form-urlencoded还是我需要配置Swashbuckle以支持这种应用程序类型?

OzB*_*Bob 1

Swashbuckle 无法满足开箱即用的“消耗”需求,需要自定义扩展,就像@domaindrivendev 的 GitHub 项目的这一部分中的扩展一样

共有三个步骤:

  1. 创建参数属性
  2. 创建扩展
  3. 向 Swashbuckle 添加指令以处理新扩展
  4. 向控制器方法中的参数添加属性

我将在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);
    }
}
Run Code Online (Sandbox Code Playgroud)

2 添加UrlFormDataParams.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.
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

3 更新Swagger.config

 //Add UrlEncoded form data support for Controller Actions that have FromBody attribute in a parameter
c.OperationFilter<AddUrlFormDataParams>();
Run Code Online (Sandbox Code Playgroud)

4.为Controller方法中的参数添加属性

[FromFormDataBody]OpenIdConnectRequest request
Run Code Online (Sandbox Code Playgroud)