Example #1
0
        public override Task WriteResponseBodyAsync(OutputFormatterWriteContext context)
        {
            SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Local;

            var objectType = context.Object.GetType();

            var root = RootObjectHelper.GetRootFieldName(objectType, false, this.SerializerSettings.ContractResolver);
            var obj  = new ExpandoObject() as IDictionary <string, Object>;

            obj[root] = context.Object;
            //context.Object = obj as object;

            var ctx = new OutputFormatterWriteContext(context.HttpContext, context.WriterFactory, objectType, obj);

            return(base.WriteResponseBodyAsync(ctx));
        }
        public object ReadFromStream(InputFormatterContext context, StreamReader reader)
        {
            SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Local;
            var type = context.ModelType;

            using (reader)
            {
                try
                {
                    var rootName   = RootObjectHelper.GetRootFieldName(type, false, SerializerSettings.ContractResolver);
                    var jsonString = reader.ReadToEnd();
                    var jsonObject = JObject.Parse(jsonString);
                    var jsonToken  = jsonObject.SelectToken(rootName);
                    if (jsonToken == null)
                    {
                        throw new RootObjectMissingException($"Root object with name {rootName} is missing in the input parameter. If there is a root object, then check the accuracy of spelling and casing.", type.Name);
                    }

                    var dataObject = JsonConvert.DeserializeObject(jsonToken.ToString(), type, SerializerSettings);
                    if (dataObject == null)
                    {
                        throw new BadRootObjectException("Input parameter does not follow the structure with the root object.", type.Name);
                    }

                    return(dataObject);
                }
                catch (RootObjectException rootEx)
                {
                    context.ModelState.TryAddModelError(String.Empty, rootEx.Message);
                    throw;
                }
                catch (JsonSerializationException jsonEx)
                {
                    context.ModelState.TryAddModelError(String.Empty, jsonEx.Message);
                    throw new BadRootObjectException(String.Format("Input parameter does not follow the structure with the root object : {0}", jsonEx.Message), type.Name);
                }
                catch (Exception ex)
                {
                    context.ModelState.TryAddModelError(String.Empty, ex.Message);
                    throw;
                }
            }
        }