[英]Passing Complex Filter throw HttpApi in Asp.Net Core 3.1
我已经构建了一个 Asp.Net Core Controller 并且我想将数据将 Url 传递到我的后端。
抛出我想粘贴的 URI:filter:"[[{"field":"firstName","operator":"eq","value":"Jan"}]]
和我的 Controller:
[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 的数据没有在我的过滤器参数中反序列化。
有人有想法吗? 谢谢你的帮助。
此致
抛出我想粘贴的 URI:filter:"[[{"field":"firstName","operator":"eq","value":"Jan"}]]
您可以通过实现自定义 model binder 来实现要求,以下代码片段供您参考。
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;
}
}
Controller 动作
[HttpGet]
public ActionResult<bool> Get([FromQuery][ModelBinder(BinderType = typeof(CustomModelBinder))]List<List<FilterObject>> filter = null)
{
测试结果
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.