public void ConfigureServices(IServiceCollection services) { services.AddEntityFramework() .AddSqlite() .AddDbContext<DomainModelSqliteContext>(); services.AddEntityFramework() .AddSqlServer() .AddDbContext<DomainModelMsSqlServerContext>(); JsonOutputFormatter jsonOutputFormatter = new JsonOutputFormatter { SerializerSettings = new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore } }; services.AddMvc( options => { options.OutputFormatters.Clear(); options.OutputFormatters.Insert(0, jsonOutputFormatter); } ); // Use a SQLite database services.AddScoped<IDataAccessProvider, DataAccessSqliteProvider>(); // Use a MS SQL Server database //services.AddScoped<IDataAccessProvider, DataAccessMsSqlServerProvider>(); }
public async Task ChangesTo_DefaultSerializerSettings_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.ContractResolver = new CamelCasePropertyNamesContractResolver(); jsonFormatter.SerializerSettings.Formatting = Formatting.Indented; var outputFormatterContext = GetOutputFormatterContext(person, typeof(User)); // Act await jsonFormatter.WriteResponseBodyAsync(outputFormatterContext); // 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 IHtmlContent SerializeInternal(JsonOutputFormatter jsonOutputFormatter, object value) { var stringWriter = new StringWriter(CultureInfo.InvariantCulture); jsonOutputFormatter.WriteObject(stringWriter, value); return new HtmlString(stringWriter.ToString()); }
public void Creates_SerializerSettings_ByDefault() { // Arrange // Act var jsonFormatter = new JsonOutputFormatter(); // Assert Assert.NotNull(jsonFormatter.SerializerSettings); }
/// <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; }
/// <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); }
// For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { services.AddMvc(options => { int position = options .OutputFormatters.ToList().FindIndex(f => f is JsonOutputFormatter); var settings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }; var formatter = new JsonOutputFormatter { SerializerSettings = settings }; options.OutputFormatters.Insert(position, formatter); }); }
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); // Assert memStream.Position = 0; var after = JToken.Load(new JsonTextReader(new StreamReader(memStream))); var afterMessage = after.ToObject <string>(); Assert.Equal(beforeMessage, afterMessage); }
// 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.AddMvc(options => { options.InputFormatters.Clear(); var jsonOutputFormatter = new JsonOutputFormatter { SerializerSettings = { ContractResolver = new CamelCasePropertyNamesContractResolver(), DefaultValueHandling = DefaultValueHandling.Ignore, DateFormatHandling = DateFormatHandling.IsoDateFormat } }; options.OutputFormatters.RemoveType<JsonOutputFormatter>(); options.OutputFormatters.Insert(0, jsonOutputFormatter); }); services.AddScoped<IExampleService, ExampleService>(); services.AddScoped<ExampleFilter>(); }
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); // 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); }
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); // 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); // 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); }
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 async Task WriteToStreamAsync_UsesCorrectCharacterEncoding( string content, string encodingAsString, bool isDefaultEncoding) { // Arrange var formatter = new JsonOutputFormatter(); 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 = mediaType, }; // Act await formatter.WriteResponseBodyAsync(outputFormatterContext); // Assert var actualData = body.ToArray(); Assert.Equal(expectedData, actualData); }
public async Task ReplaceSerializerSettings_AfterSerialization_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(); // This will create a serializer - which gets cached. var outputFormatterContext1 = GetOutputFormatterContext(person, typeof(User)); await jsonFormatter.WriteResponseBodyAsync(outputFormatterContext1); // This results in a new serializer being created. jsonFormatter.SerializerSettings = new JsonSerializerSettings() { ContractResolver = new CamelCasePropertyNamesContractResolver(), Formatting = Formatting.Indented, }; var outputFormatterContext2 = GetOutputFormatterContext(person, typeof(User)); // Act await jsonFormatter.WriteResponseBodyAsync(outputFormatterContext2); // 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); }
// For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940 public IServiceProvider ConfigureServices(IServiceCollection services) { services.AddMvc() .AddMvcOptions(options => { var jsonOutputFormatter = new JsonOutputFormatter(); jsonOutputFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); options.OutputFormatters.Insert(0, jsonOutputFormatter); }); var connection = @"Server=(localdb)\v11.0;Database=Pickle;Trusted_Connection=True;"; services.AddEntityFramework() .AddSqlServer() .AddDbContext<PickleContext>(o => o.UseSqlServer(connection)); services.AddSignalR(options => { options.Hubs.EnableDetailedErrors = true; }); var builder = new ContainerBuilder(); builder.RegisterModule(new AutofacModule()); builder.Populate(services); var container = builder.Build(); return container.ResolveOptional<IServiceProvider>(); }
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); // Assert memStream.Position = 0; var after = JToken.Load(new JsonTextReader(new StreamReader(memStream))); var afterMessage = after.ToObject<string>(); Assert.Equal(beforeMessage, afterMessage); }