1

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.

8
  • I know I can create custom CustomModelBinder : IModelBinder, but how can I use default value provider then to fill my fields from body? Commented Nov 3, 2017 at 9:13
  • You can't. You either have to make your own model binder, or use different methods and action names. Commented Nov 3, 2017 at 9:15
  • Yes, I need to create my own model binder. But how can I fill then it properties using SimpleTypeModelBinder? In fact my goal is to replace field property with proxy object before initialization using Castle.Proxies. I don't think it's duplicate question Commented Nov 3, 2017 at 9:20
  • @PatrickHofman why do you think it's duplicate? I think there are 2 different questions. Commented Nov 3, 2017 at 9:39
  • For to questions you actually have to ask two separate questions. Your requirement was to use only the default model binder. The duplicate answers that question. Commented Nov 3, 2017 at 9:41

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.