Updates to hybrid model binding in ASP.NET Core 1.0

New behavior, implementation, and... name change?

 July 9, 2016


Between the time I initially wrote about hybrid model binding, later about its updated behavior, and now, a series of changes were made to make the binding behavior safer and less verbose to implement.

Why all the changes?

The repo. and NuGet package are very young and I am still refining the approach to make sure the first "official" release has the right combination of safety, ease-of-use, naming, and expandability. The current iteration meets most of these requirements. The overall name-scheme makes sense, but I am thinking whether it can get cleaned-up a little more.

What's the new default behavior?

Similar to the previous version, model properties are, by default, not bound by multiple providers. This means a value submitted in the body and URI of a request only gets bound from the body. There is a way to override this by using the IsUnsafe property (this was previously called isGreedy). The internals have been updated to apply this logic at both the model and model-property levels. Additionally, binding is explicit, so a property not utilizing the body binder will not get bound even if a value is submimtted in the request's body.

FromAttribute

This is a new, optional attribute which can be applied to a model's properties. It replaces previous FromRoute and FromQuery usage and allows finer-grained control of binding; it gives you control of what binders to apply and whether it follows the IsUnsafe-rules:

using static HybridModelBinding.Source;

public class Person
{
    [From(Route, QueryString)]
    public int Id { get; set; }
}

This means Id will first try and bind a value from the route provider, and if it does not exist, try and bind from the querystring provider.

using static HybridModelBinding.Source;

public class Person
{
    [From(Route, QueryString, IsUnsafe = Unsafe.Yes)]
    public int Id { get; set; }
}

This variation means even if the property is bound from the route provider, rebind using the querystring provider if the value exists.

Again, using the attribute is optional. All properties inherit rules defined by the default binder-instance—DefaultHybridModelBinder.

.NET Framework support

With ASP.NET Core 1.0 getting released, the few dependencies this project has already supported .NET 4.5.1, so it just made sense to add the additional framework support to the project.

Name change?

What's in a name? That which we call a rose
By any other name would smell as sweet.

I am throwing this out there in case someone wants to donate a cool project name. The current name very clearly states its intent, is not overly long, and I am not always eager to tack a trendy name onto a project just for kicks. But, if the right one comes along...