通过复杂过滤器在 Asp.Net Core 3.1 中抛出 HttpApi

Passing Complex Filter throw HttpApi in Asp.Net Core 3.1

我已经构建了一个 Asp.Net 核心控制器,我想将数据传递给 Url 我的后端。

抛出我想粘贴的URI: filter:"[[{"field":"firstName","operator":"eq","value": "Jan"}]]

所以我的 URI 看起来像:https://localhost:5001/Patient?filter=%5B%5B%7B%22field%22%3A%22firstName%22,%22operator%22%3A%22eq%22,%22value%22%3A%22Jan%22%7D%5D%5D

和我的控制器:

[HttpGet]
public ActionResult<bool> Get(
    [FromQuery] List<List<FilterObject>> filter = null)
{
            return true;
}

我的 FilterObject 看起来像:

public class FilterObject
    {
        public string Field { get; set; }
        public string Value { get; set; }
        public FilterOperator Operator { get; set; } = FilterOperator.Eq;

    }

现在的问题是我来自 URL 的数据没有在我的过滤器参数中反序列化。

有人有想法吗? 感谢您的帮助。

此致

Throw my URI I would like to paste: filter:"[[{"field":"firstName","operator":"eq","value":"Jan"}]]

您可以通过实现自定义模型绑定器来实现需求,以下代码片段供您参考。

public class CustomModelBinder : IModelBinder
{
    public Task BindModelAsync(ModelBindingContext bindingContext)
    {
        if (bindingContext == null)
        {
            throw new ArgumentNullException(nameof(bindingContext));
        }

        // ...
        // implement it based on your actual requirement
        // code logic here
        // ...

        var options = new JsonSerializerOptions
        {
            PropertyNameCaseInsensitive = true
        };
        options.Converters.Add(new JsonStringEnumConverter(JsonNamingPolicy.CamelCase));

        var model = JsonSerializer.Deserialize<List<List<FilterObject>>>(bindingContext.ValueProvider.GetValue("filter").FirstOrDefault(), options);

        bindingContext.Result = ModelBindingResult.Success(model);
        return Task.CompletedTask;
    }
}

控制器动作

[HttpGet]
public ActionResult<bool> Get([FromQuery][ModelBinder(BinderType = typeof(CustomModelBinder))]List<List<FilterObject>> filter = null)
{

测试结果