System.Net.Http.Formatting.BetterJsonMediaTypeFormatter.OnReadFromStreamAsync C# (CSharp) Method

OnReadFromStreamAsync() protected method

Called during deserialization to read an object of the specified type from the specified stream.
protected OnReadFromStreamAsync ( Type type, Stream stream, HttpContentHeaders contentHeaders, FormatterContext formatterContext ) : Task
type Type The type of object to read.
stream System.IO.Stream The from which to read.
contentHeaders System.Net.Http.Headers.HttpContentHeaders The for the content being written.
formatterContext FormatterContext
return Task
        protected override Task<object> OnReadFromStreamAsync(Type type, Stream stream, HttpContentHeaders contentHeaders, FormatterContext formatterContext)
        {
            if (type == null)
            {
                throw new ArgumentNullException("type");
            }

            if (stream == null)
            {
                throw new ArgumentNullException("stream");
            }

            var t = new TaskCompletionSource<object>();
            t.SetResult(new Func<object>(() =>
            {
                // If content length is 0 then return default value for this type
                if (contentHeaders != null && contentHeaders.ContentLength == 0)
                {
                    return null;
                }

                // Get the character encoding for the content
                Encoding effectiveEncoding = Encoding.UTF8;

                try
                {
                    using (JsonTextReader jsonTextReader = new JsonTextReader(new StreamReader(stream, effectiveEncoding)) { CloseInput = false })
                    {
                        JsonSerializer jsonSerializer = JsonSerializer.Create(_jsonSerializerSettings);
                        return jsonSerializer.Deserialize(jsonTextReader, type);
                    }
                }
                catch (Exception)
                {
                    return null;
                }
            })());
            return t.Task;
        }