Custom Model Binding doesn’t succeed even when model is bound correctly

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?

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật