What is the easiest way to use inheritance in action using ASP.NET CORE MVC?
For example, I have 3 classes:
public class Common { public string CommonField { get; set; } } public class A : Common { public string FieldA { get; set; } } public class B : Common { public string FieldB { get; set; } } I have controller action
IActionResult Post([FromBody] [ModelBinder(BinderType = typeof(MyCustomeBinder))] Common field) { //process field here } what is the best way to replace field initialization(based on some query parameter (for example, type=a)) in action before binding? I still need all properties to be filled from body.
I already have something like:
public class MyCustomBinder : IModelBinder { public Task BindModelAsync(ModelBindingContext bindingContext) { switch (bindingContext.HttpContext.Request.Headers["type"]) { case "a": bindingContext.Result = ModelBindingResult.Success(new A()); break; case "b": bindingContext.Result = ModelBindingResult.Success(new B()); break; default: } return TaskCache.CompletedTask; } } It's correct object coming to action, but all fields are empty.
CustomModelBinder : IModelBinder, but how can I use default value provider then to fill my fields from body?fieldproperty with proxy object before initialization using Castle.Proxies. I don't think it's duplicate question