namespace EnVisage.Code.ModelBinders { using Newtonsoft.Json.Linq; using NLog; using System; using System.IO; using System.Web.Mvc; public class JsonModelBinderBase : IModelBinder where T : class, new() { public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { try { // check if it is json content is passed if (!controllerContext.HttpContext.Request.ContentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase)) return null; var stream = controllerContext.HttpContext.Request.InputStream; if (stream == null) return null; stream.Position = 0; using (var reader = new StreamReader(stream)) { var json = reader.ReadToEnd(); var modelName = bindingContext.ModelName; var modelContent = JObject.Parse(json)[modelName]; var model = modelContent.ToObject(); return model; } } catch (Exception ex) { var logger = LogManager.GetCurrentClassLogger(); logger?.Fatal(ex); return null; } } } }