Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Bind complex type objects from body by default on ASP.NET Core 1
using Microsoft.AspNet.Mvc.ApplicationModels;
using Microsoft.AspNet.Mvc.ModelBinding;
using System;
namespace Foo.Web.Infrastructure.Conventions
{
public class ComplexTypeConvention : IActionModelConvention
{
public void Apply(ActionModel action)
{
foreach (var parameter in action.Parameters)
{
var paramType = parameter.ParameterInfo.ParameterType;
if (parameter.BindingInfo == null && (IsSimpleType(paramType) || IsSimpleUnderlyingType(paramType)) == false)
{
parameter.BindingInfo = new BindingInfo
{
BindingSource = BindingSource.Body
};
}
}
}
private static bool IsSimpleType(Type type)
{
return type.IsPrimitive ||
type.Equals(typeof(string)) ||
type.Equals(typeof(DateTime)) ||
type.Equals(typeof(Decimal)) ||
type.Equals(typeof(Guid)) ||
type.Equals(typeof(DateTimeOffset)) ||
type.Equals(typeof(TimeSpan));
}
private static bool IsSimpleUnderlyingType(Type type)
{
Type underlyingType = Nullable.GetUnderlyingType(type);
if (underlyingType != null)
{
type = underlyingType;
}
return IsSimpleType(type);
}
}
}
@cecilphillip

This comment has been minimized.

Show comment Hide comment
@cecilphillip

cecilphillip Apr 12, 2016

Using RC1 with a dnxcore50 target, IsPrimitive is not available off of Type.

  • Add using System.Reflection
  • Update line 26 to type.GetTypeInfo().IsPrimitive

Using RC1 with a dnxcore50 target, IsPrimitive is not available off of Type.

  • Add using System.Reflection
  • Update line 26 to type.GetTypeInfo().IsPrimitive
@vebbo2

This comment has been minimized.

Show comment Hide comment
@vebbo2

vebbo2 Aug 16, 2016

@tugberkugurlu Hi, can you provide a snippet how to actually use this convention? Where and how should I bind it?

vebbo2 commented Aug 16, 2016

@tugberkugurlu Hi, can you provide a snippet how to actually use this convention? Where and how should I bind it?

@adnanofpk

This comment has been minimized.

Show comment Hide comment
@adnanofpk

adnanofpk Jun 28, 2017

@vebbo2 Add the following line in startup.cs
services.AddMvc(options =>
{
options.Conventions.Add(new ComplexTypeConvention());
});

@vebbo2 Add the following line in startup.cs
services.AddMvc(options =>
{
options.Conventions.Add(new ComplexTypeConvention());
});

@nefcanto

This comment has been minimized.

Show comment Hide comment
@nefcanto

nefcanto Mar 4, 2018

I had a similar convention, that worked for a while. But now it's not working and it's not hitting any breakpoints and I only get null values on complex type parameters. Any ideas?

nefcanto commented Mar 4, 2018

I had a similar convention, that worked for a while. But now it's not working and it's not hitting any breakpoints and I only get null values on complex type parameters. Any ideas?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment