public JsonHalOutputFormatter(JsonSerializerSettings serializerSettings, IEnumerable<string> halJsonMediaTypes = null) {
            if(halJsonMediaTypes == null) halJsonMediaTypes = new string[] { HalJsonType };

            this.jsonFormatter = new JsonOutputFormatter(serializerSettings, ArrayPool<Char>.Create());

            this.halJsonMediaTypes = halJsonMediaTypes;
        }
Beispiel #2
0
        private IHtmlContent SerializeInternal(JsonOutputFormatter jsonOutputFormatter, object value)
        {
            var stringWriter = new StringWriter(CultureInfo.InvariantCulture);
            jsonOutputFormatter.WriteObject(stringWriter, value);

            return new HtmlString(stringWriter.ToString());
        }
        public async Task ChangesTo_SerializerSettings_AffectSerialization()
        {
            // Arrange
            var person = new User() { FullName = "John", age = 35 };
            var outputFormatterContext = GetOutputFormatterContext(person, typeof(User));

            var settings = new JsonSerializerSettings
            {
                ContractResolver = new CamelCasePropertyNamesContractResolver(),
                Formatting = Formatting.Indented,
            };
            var expectedOutput = JsonConvert.SerializeObject(person, settings);
            var jsonFormatter = new JsonOutputFormatter(settings, ArrayPool<char>.Shared);

            // Act
            await jsonFormatter.WriteResponseBodyAsync(outputFormatterContext, Encoding.UTF8);

            // Assert
            var body = outputFormatterContext.HttpContext.Response.Body;

            Assert.NotNull(body);
            body.Position = 0;

            var content = new StreamReader(body, Encoding.UTF8).ReadToEnd();
            Assert.Equal(expectedOutput, content);
        }
Beispiel #4
0
        /// <summary>
        /// Initializes a new instance of <see cref="JsonHelper"/> that is backed by <paramref name="jsonOutputFormatter"/>.
        /// </summary>
        /// <param name="jsonOutputFormatter">The <see cref="JsonOutputFormatter"/> used to serialize JSON.</param>
        public JsonHelper(JsonOutputFormatter jsonOutputFormatter)
        {
            if (jsonOutputFormatter == null)
            {
                throw new ArgumentNullException(nameof(jsonOutputFormatter));
            }

            _jsonOutputFormatter = jsonOutputFormatter;
        }
        public static void AddJsonpOutputFormatter(this MvcOptions mvcOptions, JsonOutputFormatter jsonFormatter = null, string callbackQueryParameter = null)
        {
            jsonFormatter = jsonFormatter ?? mvcOptions.OutputFormatters.OfType<JsonOutputFormatter>().FirstOrDefault();

            if (jsonFormatter == null) throw new Exception("JSON formatter must be provided or registered in MvcOptions");

            callbackQueryParameter = callbackQueryParameter ?? "callback";
            mvcOptions.FormatterMappings.SetMediaTypeMappingForFormat(callbackQueryParameter, "text/javascript");
            mvcOptions.OutputFormatters.Insert(0, new JsonpMediaTypeFormatter(jsonFormatter, callbackQueryParameter));
        }
Beispiel #6
0
        /// <inheritdoc />
        public IHtmlContent Serialize(object value, JsonSerializerSettings serializerSettings)
        {
            if (serializerSettings == null)
            {
                throw new ArgumentNullException(nameof(serializerSettings));
            }

            var jsonOutputFormatter = new JsonOutputFormatter(serializerSettings);

            return SerializeInternal(jsonOutputFormatter, value);
        }
Beispiel #7
0
        /// <summary>
        /// Initializes a new instance of <see cref="JsonHelper"/> that is backed by <paramref name="jsonOutputFormatter"/>.
        /// </summary>
        /// <param name="jsonOutputFormatter">The <see cref="JsonOutputFormatter"/> used to serialize JSON.</param>
        /// <param name="charPool">
        /// The <see cref="ArrayPool{Char}"/> for use with custom <see cref="JsonSerializerSettings"/> (see
        /// <see cref="Serialize(object, JsonSerializerSettings)"/>).
        /// </param>
        public JsonHelper(JsonOutputFormatter jsonOutputFormatter, ArrayPool<char> charPool)
        {
            if (jsonOutputFormatter == null)
            {
                throw new ArgumentNullException(nameof(jsonOutputFormatter));
            }
            if (charPool == null)
            {
                throw new ArgumentNullException(nameof(charPool));
            }

            _jsonOutputFormatter = jsonOutputFormatter;
            _charPool = charPool;
        }
        public JsonpMediaTypeFormatter(JsonOutputFormatter jsonMediaTypeFormatter, string callbackQueryParameter = null)
        {
            if (jsonMediaTypeFormatter == null)
            {
                throw new ArgumentNullException(nameof(jsonMediaTypeFormatter));
            }

            _jsonMediaTypeFormatter = jsonMediaTypeFormatter;
            _callbackQueryParameter = callbackQueryParameter ?? "callback";

            SupportedMediaTypes.Add(_textJavaScript);
            SupportedMediaTypes.Add(_applicationJavaScript);
            SupportedMediaTypes.Add(_applicationJsonp);
            foreach (var encoding in _jsonMediaTypeFormatter.SupportedEncodings)
            {
                SupportedEncodings.Add(encoding);
            }
        }
        public IActionResult ReturnsIndentedJson()
        {
            var user = new User()
            {
                Id = 1,
                Alias = "john",
                description = "Administrator",
                Designation = "Administrator",
                Name = "John Williams"
            };

            var jsonFormatter = new JsonOutputFormatter();
            jsonFormatter.SerializerSettings.Formatting = Formatting.Indented;

            var objectResult = new ObjectResult(user);
            objectResult.Formatters.Add(jsonFormatter);

            return objectResult;
        }
        public async Task WriteToStreamAsync_RoundTripsJToken()
        {
            // Arrange
            var beforeMessage          = "Hello World";
            var formatter              = new JsonOutputFormatter();
            var before                 = new JValue(beforeMessage);
            var memStream              = new MemoryStream();
            var outputFormatterContext = GetOutputFormatterContext(
                beforeMessage,
                typeof(string),
                "application/json; charset=utf-8",
                memStream);

            // Act
            await formatter.WriteResponseBodyAsync(outputFormatterContext, Encoding.UTF8);

            // Assert
            memStream.Position = 0;
            var after        = JToken.Load(new JsonTextReader(new StreamReader(memStream)));
            var afterMessage = after.ToObject <string>();

            Assert.Equal(beforeMessage, afterMessage);
        }
        public async Task ChangesTo_DefaultSerializerSettings_AfterSerialization_NoEffect()
        {
            // Arrange
            var person = new User()
            {
                Name = "John", Age = 35
            };
            var expectedOutput = JsonConvert.SerializeObject(
                person,
                SerializerSettingsProvider.CreateSerializerSettings());

            var jsonFormatter = new JsonOutputFormatter();

            // This will create a serializer - which gets cached.
            var outputFormatterContext1 = GetOutputFormatterContext(person, typeof(User));
            await jsonFormatter.WriteResponseBodyAsync(outputFormatterContext1, Encoding.UTF8);

            // These changes should have no effect.
            jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
            jsonFormatter.SerializerSettings.Formatting       = Formatting.Indented;

            var outputFormatterContext2 = GetOutputFormatterContext(person, typeof(User));

            // Act
            await jsonFormatter.WriteResponseBodyAsync(outputFormatterContext2, Encoding.UTF8);

            // Assert
            var body = outputFormatterContext2.HttpContext.Response.Body;

            Assert.NotNull(body);
            body.Position = 0;

            var content = new StreamReader(body, Encoding.UTF8).ReadToEnd();

            Assert.Equal(expectedOutput, content);
        }
        public async Task CustomSerializerSettingsObject_TakesEffect()
        {
            // Arrange
            var person = new User()
            {
                Name = "John", Age = 35
            };
            var expectedOutput = JsonConvert.SerializeObject(person, new JsonSerializerSettings()
            {
                ContractResolver = new CamelCasePropertyNamesContractResolver(),
                Formatting       = Formatting.Indented
            });

            var jsonFormatter = new JsonOutputFormatter();

            jsonFormatter.SerializerSettings = new JsonSerializerSettings()
            {
                ContractResolver = new CamelCasePropertyNamesContractResolver(),
                Formatting       = Formatting.Indented
            };

            var outputFormatterContext = GetOutputFormatterContext(person, typeof(User));

            // Act
            await jsonFormatter.WriteResponseBodyAsync(outputFormatterContext, Encoding.UTF8);

            // Assert
            var body = outputFormatterContext.HttpContext.Response.Body;

            Assert.NotNull(body);
            body.Position = 0;

            var content = new StreamReader(body, Encoding.UTF8).ReadToEnd();

            Assert.Equal(expectedOutput, content);
        }
        private static Encoding CreateOrGetSupportedEncoding(
            JsonOutputFormatter formatter,
            string encodingAsString,
            bool isDefaultEncoding)
        {
            Encoding encoding = null;
            if (isDefaultEncoding)
            {
                encoding = formatter.SupportedEncodings
                               .First((e) => e.WebName.Equals(encodingAsString, StringComparison.OrdinalIgnoreCase));
            }
            else
            {
                encoding = Encoding.GetEncoding(encodingAsString);
                formatter.SupportedEncodings.Add(encoding);
            }

            return encoding;
        }
 public FallbackOnTypeBasedMatchController(IOptions<MvcOptions> mvcOptions)
 {
     _mvcOptions = mvcOptions;
     _jsonOutputFormatter = mvcOptions.Value.OutputFormatters.OfType<JsonOutputFormatter>().First();
 }
        public async Task WriteToStreamAsync_RoundTripsJToken()
        {
            // Arrange
            var beforeMessage = "Hello World";
            var formatter = new JsonOutputFormatter(new JsonSerializerSettings(), ArrayPool<char>.Shared);
            var before = new JValue(beforeMessage);
            var memStream = new MemoryStream();
            var outputFormatterContext = GetOutputFormatterContext(
                beforeMessage,
                typeof(string),
                "application/json; charset=utf-8",
                memStream);

            // Act
            await formatter.WriteResponseBodyAsync(outputFormatterContext, Encoding.UTF8);

            // Assert
            memStream.Position = 0;
            var after = JToken.Load(new JsonTextReader(new StreamReader(memStream)));
            var afterMessage = after.ToObject<string>();

            Assert.Equal(beforeMessage, afterMessage);
        }
        public async Task WriteToStreamAsync_UsesCorrectCharacterEncoding(
            string content,
            string encodingAsString,
            bool isDefaultEncoding)
        {
            // Arrange
            var formatter = new JsonOutputFormatter(new JsonSerializerSettings(), ArrayPool<char>.Shared);
            var formattedContent = "\"" + content + "\"";
            var mediaType = MediaTypeHeaderValue.Parse(string.Format("application/json; charset={0}", encodingAsString));
            var encoding = CreateOrGetSupportedEncoding(formatter, encodingAsString, isDefaultEncoding);
            var expectedData = encoding.GetBytes(formattedContent);


            var body = new MemoryStream();
            var actionContext = GetActionContext(mediaType, body);

            var outputFormatterContext = new OutputFormatterWriteContext(
                actionContext.HttpContext,
                new TestHttpResponseStreamWriterFactory().CreateWriter,
                typeof(string),
                content)
            {
                ContentType = new StringSegment(mediaType.ToString()),
            };

            // Act
            await formatter.WriteResponseBodyAsync(outputFormatterContext, Encoding.GetEncoding(encodingAsString));

            // Assert
            var actualData = body.ToArray();
            Assert.Equal(expectedData, actualData);
        }
Beispiel #17
0
 public JsonFormatterController(ArrayPool<char> charPool)
 {
     _indentingFormatter = new JsonOutputFormatter(_indentedSettings, charPool);
 }
Beispiel #18
0
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddLogging();
            //services.AddGlimpse();

            services.AddDbContext<MyWishesDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

            services.AddMultitenancy<MultiTenancyResolver>().Configure<MultiTenancyOptions>(opt =>
            {
                opt.Resolvers.Add(new UrlTenantResolver() { TenantsSources = new[] { new MemoryTenantsSource() } });
            });

            services.AddMvc(options => {
                var formatter = new JsonOutputFormatter
                {
                    SerializerSettings = { ContractResolver = new CamelCasePropertyNamesContractResolver() }
                };
                options.OutputFormatters.Insert(0, formatter);
            });
            services.AddMyWishesDbContext();
            services.AddTransient<ITenantsService, TenantsService>();
            services.AddTransient<IWishDaysService, WishDaysService>();
            services.AddTransient<IWishItemsService, WishItemsService>();
            //services.AddTransient<IUserContextService>(new FakeUserContextService(Guid.NewGuid()));
        }