2

我已经构建了一个 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 中的数据没有在我的过滤器参数中反序列化。

有人有想法吗?谢谢你的帮助。

此致

4

1 回答 1

1

抛出我想粘贴的 URI: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)
{

测试结果

在此处输入图像描述

于 2020-05-07T06:10:48.443 回答