自定义模型绑定器未从 Swagger 调用 UI

Custom Model Binder not invoking from Swagger UI

我在 WebApi 项目中使用 .Net framework 4.6.1 和 Swashbuckle 5.3.2 版。 Swagger UI 没有提供将输入作为请求主体发送到我的 POST Api 的选项,它使用自定义模型活页夹。

- 使用的型号:

    [ModelBinder(typeof(FieldValueModelBinder))]
    public class Employee
    {
        public int EmployeeID { get; set; }
        public string EmployeeName { get; set; }
        public string City { get; set; }
    }

- API Post 使用的方法:

    [HttpPost]
    // POST: api/Employee
    public HttpResponseMessage Post([ModelBinder(typeof(FieldValueModelBinder))]Employee emp)
    {
        if (!ModelState.IsValid)
            return Request.CreateResponse(HttpStatusCode.BadRequest, "Please provide valid input");
        else
            //Add Employee logic here
            return Request.CreateResponse(HttpStatusCode.OK, "Employee added sucessfully");
    }

- 使用的模型绑定器:

public class FieldValueModelBinder : System.Web.Http.ModelBinding.IModelBinder
{
    /// <summary>
    /// Store received data in API in KeyValuePair
    /// </summary>
    private List<KeyValuePair<string, string>> kvps;

    /// <summary>
    /// Storing error while binding data in Model class
    /// </summary>
    private Dictionary<string, string> dictionaryErrors = new Dictionary<string, string>();

    /// <summary>
    /// Implementing Base method and binding received data in API to its respected property in Model class
    /// </summary>
    /// <param name="actionContext">Http Action Context</param>
    /// <param name="bindingContext">Model Binding Context</param>
    /// <returns>True if no error while binding. False if any error occurs during model binding</returns>
    public bool BindModel(HttpActionContext actionContext, System.Web.Http.ModelBinding.ModelBindingContext bindingContext)
    {
        try
        {
            var bodyString = actionContext.Request.Content.ReadAsStringAsync().Result;
            if (actionContext.Request.Method.Method.ToUpper().Equals("GET"))
            {
                var uriContext = HttpUtility.ParseQueryString(actionContext.Request.RequestUri.Query);
                if (uriContext.HasKeys())
                {
                    this.kvps = uriContext.AllKeys.ToDictionary(k => k, k => uriContext[k]).ToList<KeyValuePair<string, string>>();
                }
            }
            else if (!string.IsNullOrEmpty(bodyString))
            {
                this.kvps = this.ConvertToKvps(bodyString);
            }
            else
            {
                bindingContext.ModelState.AddModelError(bindingContext.ModelName, "Please provide valid input data.");
                return false;
            }
        }
        catch (Exception ex)
        {
            bindingContext.ModelState.AddModelError(bindingContext.ModelName, "Please provide data in a valid format.");
            return false;
        }

        // Initiate primary object
        var obj = Activator.CreateInstance(bindingContext.ModelType);
        try
        {
            this.SetPropertyValues(obj);
        }
        catch (Exception ex)
        {
            if (this.dictionaryErrors.Any())
            {
                foreach (KeyValuePair<string, string> keyValuePair in this.dictionaryErrors)
                {
                    bindingContext.ModelState.AddModelError(keyValuePair.Key, keyValuePair.Value);
                }
            }
            else
            {
                bindingContext.ModelState.AddModelError("Internal Error", ex.Message);
            }

            this.dictionaryErrors.Clear();
            return false;
        }

        // Assign completed Mapped object to Model
        bindingContext.Model = obj;
        return true;
    }

我面临以下问题:

尝试使用 Postman,API 工作正常,我们能够在请求正文中传递输入并获得正确的输出。自定义模型绑定也可以工作,并在模型状态无效时填充错误消息,然后我们可以使用这些消息发送响应。

需要更改什么才能从 Swagger UI 调用自定义模型绑定器,同时 post 在请求正文中将输入数据 API。请建议。

您可以使用 IDocumentFilter 代码来做到这一点:

private class ApplyDocumentVendorExtensions : IDocumentFilter
{
    public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry s, IApiExplorer a)
    {
        if (swaggerDoc != null)
        {
            foreach (var path in swaggerDoc.paths)
            {
                if (path.Value.post != null && path.Value.post.parameters != null )
                {
                    var parameters = path.Value.post.parameters;
                    if (parameters.Count == 3 && parameters[0].name.StartsWith("emp"))
                    {
                        path.Value.post.parameters = EmployeeBodyParam;
                    }
                }
            }
        }
    }

    private IList<Parameter> EmployeeBodyParam
    {
        get
        {
            return new List<Parameter>
            {
                new Parameter {
                    name = "emp",
                    @in = "body",
                    required = true,
                    schema = new Schema {
                        @ref = "#/definitions/Employee"
                    }
                }
            };
        }
    }
}