public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            //
            // Get a shortcut to context objects
            //
            var request = filterContext.HttpContext.Request;
            var server = filterContext.HttpContext.Server;
            string contentType = request.ContentType;

            if (string.IsNullOrEmpty(contentType)) return;

            if (!contentType.Contains("application/json")) return;

            string paramValue = request.QueryString.ToString();

            if (request.RequestType == "GET")
                paramValue = server.UrlDecode(paramValue);
            else
                using (var reader = new StreamReader(request.InputStream))
                    paramValue = reader.ReadToEnd();

            var serializer = new JavaScriptSerializer();
            var rawResult = (IDictionary<string, object>)serializer.DeserializeObject(paramValue);

            foreach (var item in filterContext.ActionDescriptor.GetParameters())
            {
                var deserializeMethod = serializer.GetType()
                .GetMethods().First(m => m.Name == "ConvertToType")
                .MakeGenericMethod(item.ParameterType);

                filterContext.ActionParameters[item.ParameterName] = deserializeMethod.Invoke(serializer, new[] { rawResult[item.ParameterName] });
            }
        }
Esempio n. 2
0
 public JsonService()
 {
     _serializer = new JavaScriptSerializer();
     _method = _serializer
         .GetType()
         .GetMethods(BindingFlags.Instance | BindingFlags.Public)
         .First(m => m.Name.EndsWith("Deserialize"));
 }
        public static object Deserialize(string jsonText, Type valueType)
        {
            // *** Have to use Reflection with a 'dynamic' non constant type instance
            JavaScriptSerializer ser = new JavaScriptSerializer();

            object result = ser.GetType()
                               .GetMethod("Deserialize")
                               .MakeGenericMethod(valueType)
                              .Invoke(ser, new object[1] { jsonText });
            return result;
        }