I'm creating a custom ModelBinder in .NET Core 1.1.0, and I think I have it mostly figured out. I want to use this binder only when I specifically want to, but I can't figure out how to accomplish this. I want this model binder to be ignored when I don't call it, but when I call it I want all others to be ignored. How can I accomplish this?
The two things that seem feasible are the parameter attributes [Bind]
and [ModelBinder]
, but neither of these really works.
I first tried the below:
[HttpGet]
public async Task<IActionResult> Get([Bind("test")] int userId)
{
// stuff
}
When my custom IModelBinderProvider
is hit, the ModelBinderProviderContext
contains a BindingInfo
property, which in turn contains an IPropertyFilterProvider
. When debugging, that filter provider contains a collection called Include
with my value of test
. There doesn't appear to be any way to check for that programmatically, however--there's no way that I can find to actually access that collection. It's null if nothing is set, so I could hypothetically check for null, but that's very messy and isn't a good idea.
To illustrate, here's the debugger info for the ModelBinderProviderContext
:
Next, I tried using this code:
[HttpGet]
public async Task<IActionResult> Get(
[ModelBinder(BinderType = typeof(MyModelBinder))] int userId
)
{
// stuff
}
This attribute appears to have no effect whatsoever. It does not force MyModelBinder
to be used; model binders are used in the order specified in Startup.cs
(the list in MvcOptions
).
The PropertyFilterProvider
contains a BindAttribute
instance which implements the IPropertyFilterProvider
interface. You could cast the instance to a BindAttribute
and access the Include
property:
var bindAttribute = context.BindingInfo.PropertyFilterProvider as BindAttribute;
var include = bindAttribute?.Include;
Keep in mind that the cast may not succeed, resulting in bindingAttribute
being null
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.