-
-
Save yevhen/5380e9f537966ec562bad7b6bc8ee8b9 to your computer and use it in GitHub Desktop.
Bind complex type objects from body by default on ASP.NET Core 1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment