JSON属性未绑定到ASP.NET MVC 5 Post请求中的JSON.NET PropertyName

时间:2017-02-04 23:01:24

标签: json asp.net-mvc asp.net-mvc-5 json.net

我正在敲打我的头,听听为什么我的属性ReCaptchaResponse JSONProperty不会绑定到我的模型。其他人只是找到了,我的JSON Value Provider类就可以了。有任何线索吗?它始终为NULL。

Ajax请求

{"Name":"Joe","Email":"","Message":"","g-recaptcha-response":"data"}

ContactUsController.cs

 [HttpPost]
        public virtual ActionResult Index(ContactUsModel model)
        {
            _contactUsService.ContactUs(model);

            return Json(new SuccessResponse("Submitted Successfully"));
        }

ContactUsMode.cs

[JsonObject, DataContract]
    public class ContactUsModel
    {
        public string Name { get; set; }
        public string Email { get; set; }
        public string Message { get; set; }

        [JsonProperty(PropertyName = "g-recaptcha-response"), DataMember(Name = "g-recaptcha-response")]
        public string ReCaptchaResponse { get; set; }
    }

JsonNetValueProviderFactory.cs

namespace Tournaments.Models.Mvc
{
    public class JsonNetValueProviderFactory : ValueProviderFactory
    {
        public override IValueProvider GetValueProvider(ControllerContext controllerContext)
        {
            // first make sure we have a valid context
            if (controllerContext == null)
                throw new ArgumentNullException("controllerContext");

            // now make sure we are dealing with a json request
            if (!controllerContext.HttpContext.Request.ContentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase))
                return null;

            // get a generic stream reader (get reader for the http stream)
            var streamReader = new StreamReader(controllerContext.HttpContext.Request.InputStream);
            // convert stream reader to a JSON Text Reader
            var jsonReader = new JsonTextReader(streamReader);
            // tell JSON to read
            if (!jsonReader.Read())
                return null;

            // make a new Json serializer
            var jsonSerializer = new JsonSerializer();
            jsonSerializer.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
            // add the dyamic object converter to our serializer
            jsonSerializer.Converters.Add(new ExpandoObjectConverter());

            // use JSON.NET to deserialize object to a dynamic (expando) object
            Object jsonObject;
            // if we start with a "[", treat this as an array
            if (jsonReader.TokenType == JsonToken.StartArray)
                jsonObject = jsonSerializer.Deserialize<List<ExpandoObject>>(jsonReader);
            else
                jsonObject = jsonSerializer.Deserialize<ExpandoObject>(jsonReader);

            // create a backing store to hold all properties for this deserialization
            var backingStore = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
            // add all properties to this backing store
            AddToBackingStore(backingStore, String.Empty, jsonObject);
            // return the object in a dictionary value provider so the MVC understands it
            return new DictionaryValueProvider<object>(backingStore, CultureInfo.CurrentCulture);
        }

        private static void AddToBackingStore(Dictionary<string, object> backingStore, string prefix, object value)
        {
            var d = value as IDictionary<string, object>;
            if (d != null)
            {
                foreach (KeyValuePair<string, object> entry in d)
                {
                    AddToBackingStore(backingStore, MakePropertyKey(prefix, entry.Key), entry.Value);
                }
                return;
            }

            var l = value as IList;
            if (l != null)
            {
                for (int i = 0; i < l.Count; i++)
                {
                    AddToBackingStore(backingStore, MakeArrayKey(prefix, i), l[i]);
                }
                return;
            }

            // primitive
            backingStore[prefix] = value;
        }

        private static string MakeArrayKey(string prefix, int index)
        {
            return prefix + "[" + index.ToString(CultureInfo.InvariantCulture) + "]";
        }

        private static string MakePropertyKey(string prefix, string propertyName)
        {
            return (String.IsNullOrEmpty(prefix)) ? propertyName : prefix + "." + propertyName;
        }
    }
}

1 个答案:

答案 0 :(得分:0)

尝试ModelBinder。由于ExpandoObject,ValueProviderFactory无法正常工作。

internal class JsonNetModelBinder : IModelBinder
    {
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            controllerContext.HttpContext.Request.InputStream.Position = 0;
            var stream = controllerContext.RequestContext.HttpContext.Request.InputStream;
            var readStream = new StreamReader(stream, Encoding.UTF8);
            var json = readStream.ReadToEnd();
            return JsonConvert.DeserializeObject(json, bindingContext.ModelType);
        }
    }

ContactUsController.cs

[HttpPost]
public virtual ActionResult Index([ModelBinder(typeof(JsonNetModelBinder))]ContactUsModel model)
{
    _contactUsService.ContactUs(model);

    return Json(new SuccessResponse("Submitted Successfully"));
}