Reputation: 5690
I have an ASP.NET Core Web API.
I an endpoint which accepts a model called Search. It has property called Query of type Expression. This Expression object has sub classes.
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;}
}
I post the following JSON to my endpoint (content-type of application/json)
{ "query": { "fieldId": "body", "value": "cake", "operator": "matches" } }
Firstly, the query parameter is just the base Expression - A polymorphic issue!
So... I thought bespoke Model Binder.
I can set up a model binder against the Search object, but you'll note that the AndExpression can contain other Expression objects, so instead I'd like to write a binder that can be bound to "Query" on the Search Model and to Expressions on the AndExpression Model etc etc
I attempted this:
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;
}
}
Ive wired this binder up in the configureServices method of my Startup Class.
I have a break point in the ExpressionBinder and it doesn't hit!
What am I doing wrong?
Also, can I use the [ModelBinder(BinderType = typeof(ExpressionBinder))] attribute against a list of Expressions?
Upvotes: 0
Views: 1756
Reputation: 5690
So this is very explicit https://github.com/aspnet/Mvc/issues/4553
If a FromBody attribute is applied the ModelBinder attribute wont work!
Upvotes: 4