【问题标题】:Passing Complex Filter throw HttpApi in Asp.Net Core 3.1在 Asp.Net Core 3.1 中通过复杂过滤器抛出 HttpApi
【发布时间】:2020-05-06 15:30:22
【问题描述】:

我已经构建了一个 Asp.Net Core Controller,我想将 Data throw the 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 中的数据没有在我的过滤器参数中反序列化。

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

最好的问候

【问题讨论】:

    标签: c# asp.net-core controller httpapi


    【解决方案1】:

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

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

    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)
    {
    

    测试结果

    【讨论】:

    • 谢谢!这里有一点:发送 null 失败,所以我在 CustomModelBinder 中编辑了 BindModelAsync,如下所示:
    • ...if (bindingContext.ValueProvider.GetValue("filter").FirstOrDefault() != null) { var model = JsonSerializer.Deserialize>>(bindingContext. ValueProvider.GetValue("filter").FirstOrDefault(), options); bindingContext.Result = ModelBindingResult.Success(model); } else bindingContext.Result = ModelBindingResult.Success(null);
    猜你喜欢
    • 1970-01-01
    • 2021-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-18
    • 2023-03-10
    相关资源
    最近更新 更多