I’ve implemented custom model binding in an asp .net core api. It works more of the time, but is failing for some models and I’m not sure why.
Provider:
public class RequestBodyModelBinderProvider : IModelBinderProvider
{
public IModelBinder? GetBinder(ModelBinderProviderContext context)
{
try
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
if (context.Metadata.ModelType.GetTypeInfo().IsGenericType &&
context.Metadata.ModelType.GetGenericTypeDefinition() == typeof(RequestBody<>))
{
Type[] types = context.Metadata.ModelType.GetGenericArguments();
Type o = typeof(RequestBodyModelBinder<>).MakeGenericType(types);
Log.LogToDB("Creating Model", LogType.Info);
return (IModelBinder?)Activator.CreateInstance(o);
}
}
catch (Exception ex)
{
Log.LogException(ex);
}
Log.LogToDB("Could not create model", LogType.Info);
return null;
}
}
Binder:
public Task BindModelAsync(ModelBindingContext bindingContext)
{
try
{
if (bindingContext == null)
{
throw new ArgumentNullException(nameof(bindingContext));
}
RequestBody<T> request = new RequestBody<T>();
JObject? requestObject = (JObject?)bindingContext.HttpContext.Items["RequestData"];
if (requestObject == null)
{
return Task.CompletedTask;
}
T? castedObject = requestObject.ToObject<T>();
if (castedObject == null)
{
return Task.CompletedTask;
}
if (castedObject is FilterRequest fr)
{
Log.LogToDB($"Got Filter Request. Valid: {fr.IsValid()}", LogType.Info);
}
Log.LogToDB("Bound Model", LogType.Info);
request.Data = castedObject;
bindingContext.Result = ModelBindingResult.Success(request);
}
catch (Exception ex)
{
Log.LogException(ex);
}
return Task.CompletedTask;
}
Model:
public class RequestBody<T> : IValidatableObject where T : BaseRequest, new()
{
public T Data { get; set; } = new T();
public RequestBody() { }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
Log.LogToDB("Validating Object", LogType.Info);
if (Data == null)
{
Log.LogToDB("Null Data", LogType.Info);
yield return new ValidationResult("Null Data");
}
else if (!Data.IsValid())
{
Log.LogToDB("Invalid Data", LogType.Info);
yield return new ValidationResult("Invalid Data");
}
}
}
And this is how it is used:
public ActionResult Add(RequestBody<FilterRequest> body)
{
Log.LogToDB("Add Filter", LogType.Info);
}
As you can see I have logs all over the place trying to figure out what is going wrong. When the generic type of RequestBody
is a FilterRequest
it will successfully log ‘Bound Model’ (from the binder) but it will never reach Validate
in RequestBody
, the request never reaches the controller, and a 400 is returned. On the other hand, if I use a different generic type, like RequestBody<GetChartDataRequest>
everything works as expected, Validate
is called and the request makes it to the controller.
Here are the requests:
public class StoreRequest : BaseRequest, IMasterKeyRequest
{
public string MasterKey { get; set; } = "";
public FilterStoreState? FilterStoreState { get; set; }
public PasswordStoreState? PasswordStoreState { get; set; }
public ValueStoreState? ValueStoreState { get; set; }
public GroupStoreState? GroupStoreState { get; set; }
public override bool IsValid()
{
return base.IsValid() &&
!string.IsNullOrEmpty(MasterKey);
}
}
public class FilterRequest : StoreRequest
{
public Filter Filter? { get; set; }
public override bool IsValid()
{
return base.IsValid() &&
Filter != null;
}
}
public class GetChartDataRequest : BaseRequest
{
public CurrentAndSafeStructure Values { get; set; } = new CurrentAndSafeStructure();
public override bool IsValid()
{
return base.IsValid() &&
Values != null;
}
}
I’ve tested it with other types that inherit from StoreRequest
and they all fail. What is wrong with StoreRequest
that is causing my custom model binding to not fully succeeded, despite the model being bound successfully?