Skip to content

Instantly share code, notes, and snippets.

@surgicalcoder
Last active August 16, 2017 12:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save surgicalcoder/0ea53d93a6fae663bbf8024f35408a51 to your computer and use it in GitHub Desktop.
Save surgicalcoder/0ea53d93a6fae663bbf8024f35408a51 to your computer and use it in GitHub Desktop.
JsonToParametersAttribute
public class JsonToParametersAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
base.OnActionExecuting(filterContext);
var stream = filterContext.HttpContext.Request.Body;
using (var sr = new StreamReader(stream))
using (var jsonTextReader = new JsonTextReader(sr))
{
var serializer = new JsonSerializer();
var body = serializer.Deserialize<JObject>(jsonTextReader);
if (body == null) return;
foreach (var parameter in filterContext.ActionDescriptor.Parameters)
{
var jsonProperty = body.Properties().SingleOrDefault(p => p.Name == parameter.Name);
if (jsonProperty != null)
{
var param = filterContext.ActionDescriptor.Parameters.OfType<ControllerParameterDescriptor>().FirstOrDefault(e => e.Name == parameter.Name);
if (param == null)
{
continue;
}
if (!filterContext.ActionArguments.ContainsKey(parameter.Name))
{
object value;
try
{
value = jsonProperty.Value.ToObject(param.ParameterInfo.ParameterType);
}
catch (Exception)
{
value = GetDefault(param.ParameterInfo.ParameterType);
}
filterContext.ActionArguments.Add(parameter.Name, value);
}
}
}
}
}
private static object GetDefault(Type type)
{
if (type.IsValueType)
{
return Activator.CreateInstance(type);
}
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment