【发布时间】:2021-12-01 04:36:37
【问题描述】:
我有一个 ASP.NET Core Web API。
我是一个接受名为 Search 的模型的端点。它具有类型为 Expression 的称为 Query 的属性。这个 Expression 对象有子类。
public class Search {
public Expression Query{get;set;}
}
Public class Expression {
}
public class AndExpression {
public IList<Expression> Expressions {get;set;}
}
public class MatchesExpression {
public string FieldId {get;set;}
public string Value {get;set;}
public string Operator {get;set;}
}
我将以下 JSON 发布到我的端点(应用程序/json 的内容类型)
{ “询问”: { “fieldId”:“正文”, “价值”:“蛋糕”, “操作员”:“匹配” } }
首先,查询参数只是基本表达式 - 多态问题!
所以...我想定制模型活页夹。
我可以针对 Search 对象设置模型绑定器,但您会注意到 AndExpression 可以包含其他 Expression 对象,因此我想编写一个绑定到 Search 上的“Query”的绑定器模型和表达式上的 AndExpression 模型等
我试过这个:
public class Search
{
[ModelBinder(BinderType = typeof(ExpressionBinder))]
public Expression Query { get; set; }
}
public class ExpressionBinder : IModelBinder
{
public Task BindModelAsync(ModelBindingContext bindingContext)
{
throw new NotImplementedException();
}
}
public class ExpressionBinderProvider : IModelBinderProvider {
public IModelBinder GetBinder(ModelBinderProviderContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
if (context.Metadata.ModelType == typeof(Expression))
{
return new BinderTypeModelBinder(typeof(ExpressionBinder));
}
return null;
}
}
我已经在我的启动类的 configureServices 方法中连接了这个活页夹。
我在 ExpressionBinder 中有一个断点,但它没有命中!
我做错了什么?
另外,我可以对表达式列表使用 [ModelBinder(BinderType = typeof(ExpressionBinder))] 属性吗?
【问题讨论】:
-
这篇文章docs.microsoft.com/en-us/aspnet/web-api/overview/…好像说不能在属性级别应用ModelBinder属性。
-
但是这篇文章 docs.microsoft.com/en-us/aspnet/core/mvc/advanced/… 说“您可以将 ModelBinder 属性应用于单个模型属性”,所以它真的不清楚这里最好的方法是什么
标签: asp.net-core asp.net-web-api