private static void Main() { var person = new Person { Title = Title.Mr, FirstName = "Matt", Age = 99, Income = 1234 }; // Serialize using XmlDataContractSerializerOutputFormatter - works var xmlFormatter = new XmlDataContractSerializerOutputFormatter(); var result = Serialize(person, xmlFormatter, ApplicationXml); Console.WriteLine("Xml: " + result); // Serialize using NewtonsoftJsonOutputFormatter - also works var newtonsoftFormatter = new NewtonsoftJsonOutputFormatter(new Newtonsoft.Json.JsonSerializerSettings(), ArrayPool <char> .Shared, new MvcOptions()); result = Serialize(person, newtonsoftFormatter, ApplicationJson); Console.WriteLine("Newtonsoft Json: " + result); // Serialize using SystemTextJsonOutputFormatter - returns empty string :-( var systemTextJsonFormatter = new SystemTextJsonOutputFormatter(new System.Text.Json.JsonSerializerOptions()); result = Serialize(person, systemTextJsonFormatter, ApplicationJson); Console.WriteLine("System.Text.Json: " + result); Console.ReadLine(); }
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 NewtonsoftJsonOutputFormatter(settings, ArrayPool <char> .Shared, new MvcOptions(), new MvcNewtonsoftJsonOptions()); // 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); }
public static MvcOptions ConfigureJsonFormatter([NotNull] this MvcOptions thisValue, [NotNull] Action <JsonSerializerSettings> configureJson, [NotNull] ILogger logger) { thisValue.RespectBrowserAcceptHeader = true; MvcNewtonsoftJsonOptions mvcJsonOptions = new MvcNewtonsoftJsonOptions { AllowInputFormatterExceptionMessages = true }; JsonSerializerSettings settings = mvcJsonOptions.SerializerSettings; configureJson(settings); NewtonsoftJsonInputFormatter input = thisValue.InputFormatters.OfType <NewtonsoftJsonInputFormatter>() .FirstOrDefault(); if (input == null) { input = new NewtonsoftJsonInputFormatter(logger, settings, ArrayPool <char> .Shared, new DefaultObjectPoolProvider(), thisValue, mvcJsonOptions); thisValue.InputFormatters.Add(input); } NewtonsoftJsonOutputFormatter output = thisValue.OutputFormatters.OfType <NewtonsoftJsonOutputFormatter>() .FirstOrDefault(); if (output == null) { output = new NewtonsoftJsonOutputFormatter(settings, ArrayPool <char> .Shared, thisValue); thisValue.OutputFormatters.Add(output); } thisValue.FormatterMappings.SetMediaTypeMappingForFormat("json", MediaTypeHeaderValues.ApplicationJson); return(thisValue); }
public async Task WriteToStreamAsync_LargePayload_DoesNotPerformSynchronousWrites() { // Arrange var model = Enumerable.Range(0, 1000).Select(p => new User { FullName = new string('a', 5000) }); var stream = new Mock <Stream> { CallBase = true }; stream.Setup(v => v.WriteAsync(It.IsAny <byte[]>(), It.IsAny <int>(), It.IsAny <int>(), It.IsAny <CancellationToken>())) .Returns(Task.CompletedTask); stream.Setup(v => v.FlushAsync(It.IsAny <CancellationToken>())).Returns(Task.CompletedTask); stream.SetupGet(s => s.CanWrite).Returns(true); var formatter = new NewtonsoftJsonOutputFormatter(new JsonSerializerSettings(), ArrayPool <char> .Shared, new MvcOptions(), new MvcNewtonsoftJsonOptions()); var outputFormatterContext = GetOutputFormatterContext( model, typeof(string), "application/json; charset=utf-8", stream.Object); // Act await formatter.WriteResponseBodyAsync(outputFormatterContext, Encoding.UTF8); // Assert stream.Verify(v => v.WriteAsync(It.IsAny <byte[]>(), It.IsAny <int>(), It.IsAny <int>(), It.IsAny <CancellationToken>()), Times.AtLeastOnce()); stream.Verify(v => v.Write(It.IsAny <byte[]>(), It.IsAny <int>(), It.IsAny <int>()), Times.Never()); stream.Verify(v => v.Flush(), Times.Never()); Assert.NotNull(outputFormatterContext.HttpContext.Response.ContentLength); }
public static void ConfigureMvc(MvcOptions options, JsonSerializerSettings serializerSettings, ILoggerFactory loggerFactory, ArrayPool <char> charPool, ObjectPoolProvider objectPoolProvider) { NewtonsoftJsonOutputFormatter jsonOutput = options.OutputFormatters.OfType <NewtonsoftJsonOutputFormatter>().First(); options.OutputFormatters.Remove(jsonOutput); options.OutputFormatters.Add(new RPCJsonOutputFormatter(serializerSettings)); }
public async Task MvcJsonOptionsAreUsedToSetBufferThreshold() { // Arrange var person = new User() { FullName = "John", age = 35 }; Stream writeStream = null; var outputFormatterContext = GetOutputFormatterContext(person, typeof(User), writerFactory: (stream, encoding) => { writeStream = stream; return(StreamWriter.Null); }); var settings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver(), Formatting = Formatting.Indented, }; var expectedOutput = JsonConvert.SerializeObject(person, settings); var jsonFormatter = new NewtonsoftJsonOutputFormatter(settings, ArrayPool <char> .Shared, new MvcOptions(), new MvcNewtonsoftJsonOptions() { OutputFormatterMemoryBufferThreshold = 2 }); // Act await jsonFormatter.WriteResponseBodyAsync(outputFormatterContext, Encoding.UTF8); // Assert Assert.IsType <FileBufferingWriteStream>(writeStream); Assert.Equal(2, ((FileBufferingWriteStream)writeStream).MemoryThreshold); }
private IHtmlContent SerializeInternal(NewtonsoftJsonOutputFormatter jsonOutputFormatter, object value) { var stringWriter = new StringWriter(CultureInfo.InvariantCulture); jsonOutputFormatter.WriteObject(stringWriter, value); return(new HtmlString(stringWriter.ToString())); }
/// <inheritdoc /> public IHtmlContent Serialize(object value, JsonSerializerSettings serializerSettings) { if (serializerSettings == null) { throw new ArgumentNullException(nameof(serializerSettings)); } var jsonOutputFormatter = new NewtonsoftJsonOutputFormatter(serializerSettings, _charPool); return(SerializeInternal(jsonOutputFormatter, value)); }
public AbpHybridJsonOutputFormatter(SystemTextJsonOutputFormatter systemTextJsonOutputFormatter, NewtonsoftJsonOutputFormatter newtonsoftJsonOutputFormatter) { _systemTextJsonOutputFormatter = systemTextJsonOutputFormatter; _newtonsoftJsonOutputFormatter = newtonsoftJsonOutputFormatter; SupportedEncodings.Add(Encoding.UTF8); SupportedEncodings.Add(Encoding.Unicode); SupportedMediaTypes.Add(MediaTypeHeaderValues.ApplicationJson); SupportedMediaTypes.Add(MediaTypeHeaderValues.TextJson); SupportedMediaTypes.Add(MediaTypeHeaderValues.ApplicationAnyJsonSyntax); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddSingleton(Configuration); services.AddCaching(Configuration); IConfigurationSection azureADConfig = Configuration.GetSection("AzureAD"); services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.Authority = $"{azureADConfig.GetValue<string>("Authority")}/{azureADConfig.GetValue<string>("TenantId")}/"; options.Audience = azureADConfig.GetValue <string>("Audience"); }); services.AddVersionedApiExplorer( options => { options.GroupNameFormat = "'v'VVV"; options.SubstituteApiVersionInUrl = true; }); services.AddControllers() .AddNewtonsoftJson(options => { options.SerializerSettings.Formatting = Formatting.Indented; options.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver(); }) .AddMvcOptions(options => { options.OutputFormatters.RemoveType <StringOutputFormatter>(); NewtonsoftJsonOutputFormatter jFormatter = options.OutputFormatters.FirstOrDefault(f => f.GetType() == typeof(NewtonsoftJsonOutputFormatter)) as NewtonsoftJsonOutputFormatter; jFormatter?.SupportedMediaTypes.Clear(); jFormatter?.SupportedMediaTypes.Add("application/atom+json"); jFormatter?.SupportedMediaTypes.Add("application/json"); }); services.AddApiVersioning( o => { o.ReportApiVersions = true; o.AssumeDefaultVersionWhenUnspecified = true; o.DefaultApiVersion = new ApiVersion(1, 0); }); RegisterComponents(services); SwaggerSetup.ConfigureSwaggerServices(services); }
/// <summary> /// Initializes a new instance of <see cref="NewtonsoftJsonHelper"/> that is backed by <paramref name="jsonOutputFormatter"/>. /// </summary> /// <param name="jsonOutputFormatter">The <see cref="NewtonsoftJsonOutputFormatter"/> 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 NewtonsoftJsonHelper(NewtonsoftJsonOutputFormatter 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 override void OnResultExecuting(ResultExecutingContext context) { if (context.Result is ObjectResult objectResult) { var serializerSettings = new JsonSerializerSettings { ContractResolver = new DefaultContractResolver(), }; // Code from: https://github.com/aspnet/Mvc/issues/8128#issuecomment-407214518 var options = context.HttpContext.RequestServices.GetRequiredService <IOptions <MvcOptions> >(); var mvcOptions = options.Value; var jsonFormatter = new NewtonsoftJsonOutputFormatter(serializerSettings, ArrayPool <char> .Shared, mvcOptions); objectResult.Formatters.Add(jsonFormatter); } }
public JsonHalOutputFormatter( MvcOptions mvcOptions, JsonSerializerSettings serializerSettings, IEnumerable <string> halJsonMediaTypes = null) { if (halJsonMediaTypes == null) { halJsonMediaTypes = new string[] { HalJsonType } } ; this.serializerSettings = serializerSettings; this.jsonFormatter = new NewtonsoftJsonOutputFormatter(this.serializerSettings, ArrayPool <Char> .Create(), mvcOptions); this.halJsonMediaTypes = halJsonMediaTypes; }
public override void OnActionExecuted(ActionExecutedContext ctx) { if (!(ctx.Result is ObjectResult objectResult)) { return; } var serializer = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Include }; serializer.Converters.Add(new StringEnumConverter()); var formatter = new NewtonsoftJsonOutputFormatter(serializer, ctx.HttpContext.RequestServices.GetRequiredService <ArrayPool <char> >(), new MvcOptions()); objectResult.Formatters.Add(formatter); }
public async Task MvcJsonOptionsAreUsedToSetBufferThresholdFromServices() { // Arrange var person = new User() { FullName = "John", age = 35 }; Stream writeStream = null; var outputFormatterContext = GetOutputFormatterContext(person, typeof(User), writerFactory: (stream, encoding) => { writeStream = stream; return(StreamWriter.Null); }); var services = new ServiceCollection() .AddOptions() .Configure <MvcNewtonsoftJsonOptions>(o => { o.OutputFormatterMemoryBufferThreshold = 1; }) .BuildServiceProvider(); outputFormatterContext.HttpContext.RequestServices = services; var settings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver(), Formatting = Formatting.Indented, }; var expectedOutput = JsonConvert.SerializeObject(person, settings); #pragma warning disable CS0618 // Type or member is obsolete var jsonFormatter = new NewtonsoftJsonOutputFormatter(settings, ArrayPool <char> .Shared, new MvcOptions()); #pragma warning restore CS0618 // Type or member is obsolete // Act await jsonFormatter.WriteResponseBodyAsync(outputFormatterContext, Encoding.UTF8); // Assert Assert.IsType <FileBufferingWriteStream>(writeStream); Assert.Equal(1, ((FileBufferingWriteStream)writeStream).MemoryThreshold); }
public async Task WriteToStreamAsync_RoundTripsJToken() { // Arrange var beforeMessage = "Hello World"; var formatter = new NewtonsoftJsonOutputFormatter(new JsonSerializerSettings(), ArrayPool <char> .Shared, new MvcOptions(), new MvcNewtonsoftJsonOptions()); 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 void Configure(MvcOptions options) { var systemTextJsonInputFormatter = new SystemTextJsonInputFormatter( _jsonOptions.Value, _loggerFactory.CreateLogger <SystemTextJsonInputFormatter>()); var newtonsoftJsonInputFormatter = new NewtonsoftJsonInputFormatter( _loggerFactory.CreateLogger <NewtonsoftJsonInputFormatter>(), _mvcNewtonsoftJsonOptions.Value.SerializerSettings, _charPool, _objectPoolProvider, options, _mvcNewtonsoftJsonOptions.Value); options.InputFormatters.RemoveType <SystemTextJsonInputFormatter>(); options.InputFormatters.RemoveType <NewtonsoftJsonInputFormatter>(); options.InputFormatters.Add(new AbpHybridJsonInputFormatter(systemTextJsonInputFormatter, newtonsoftJsonInputFormatter)); var jsonSerializerOptions = _jsonOptions.Value.JsonSerializerOptions; if (jsonSerializerOptions.Encoder is null) { // If the user hasn't explicitly configured the encoder, use the less strict encoder that does not encode all non-ASCII characters. jsonSerializerOptions = new JsonSerializerOptions(jsonSerializerOptions) { Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping, }; } var systemTextJsonOutputFormatter = new SystemTextJsonOutputFormatter(jsonSerializerOptions); var newtonsoftJsonOutputFormatter = new NewtonsoftJsonOutputFormatter( _mvcNewtonsoftJsonOptions.Value.SerializerSettings, _charPool, options); options.OutputFormatters.RemoveType <SystemTextJsonOutputFormatter>(); options.OutputFormatters.RemoveType <NewtonsoftJsonOutputFormatter>(); options.OutputFormatters.Add(new AbpHybridJsonOutputFormatter(systemTextJsonOutputFormatter, newtonsoftJsonOutputFormatter)); }
public override void OnResultExecuting(ResultExecutingContext context) { if (context.Result is ObjectResult objectResult) { var serializerSettings = new JsonSerializerSettings { Formatting = Formatting.Indented, ContractResolver = new DefaultContractResolver() }; serializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore; serializerSettings.MaxDepth = 2; var jsonFormatter = new NewtonsoftJsonOutputFormatter( serializerSettings, ArrayPool <char> .Shared, new MvcOptions()); objectResult.Formatters.Add(jsonFormatter); } base.OnResultExecuting(context); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllers() .AddNewtonsoftJson(); services.AddOptions <MvcOptions>() .Configure <ILoggerFactory, ObjectPoolProvider>((options, loggerFactory, objectPoolProvider) => { JsonApiSerializerSettings serializerSettings = new JsonApiSerializerSettings() { NullValueHandling = NullValueHandling.Ignore }; MvcNewtonsoftJsonOptions jsonOptions = new MvcNewtonsoftJsonOptions(); NewtonsoftJsonOutputFormatter jsonApiOutputFormatter = new NewtonsoftJsonOutputFormatter(serializerSettings, ArrayPool <Char> .Shared, options); options.OutputFormatters.RemoveType <NewtonsoftJsonOutputFormatter>(); options.OutputFormatters.Add(jsonApiOutputFormatter); NewtonsoftJsonInputFormatter jsonApiInputFormatter = new NewtonsoftJsonInputFormatter(loggerFactory.CreateLogger <NewtonsoftJsonInputFormatter>(), serializerSettings, ArrayPool <Char> .Shared, objectPoolProvider, options, jsonOptions); options.InputFormatters.RemoveType <NewtonsoftJsonInputFormatter>(); options.InputFormatters.Add(jsonApiInputFormatter); }); }
public static void ConfigureMvc( MvcOptions options, JsonSerializerSettings serializerSettings, ILoggerFactory loggerFactory, ArrayPool <char> charPool, ObjectPoolProvider objectPoolProvider, MvcJsonOptions jsonOptions = null) { serializerSettings.Formatting = Formatting.Indented; serializerSettings.Converters.Add(new DateTimeOffsetFormatJsonConverter()); serializerSettings.DateParseHandling = DateParseHandling.None; options.OutputFormatters.Clear(); var jsonOutputFormatter = #if NETCOREAPP3_0 || NETCOREAPP3_1 || NET5_0 new NewtonsoftJsonOutputFormatter(serializerSettings, charPool, options); #elif NETSTANDARD2_0 || NETFRAMEWORK new JsonOutputFormatter(serializerSettings, charPool); #else #error unknown target framework #endif options.OutputFormatters.Add(jsonOutputFormatter); options.InputFormatters.Clear(); var jsonInputLogger = loggerFactory.CreateLogger <HypermediaApiJsonInputFormatter>(); options.InputFormatters.Add(new HypermediaApiJsonInputFormatter( jsonInputLogger, serializerSettings, charPool, objectPoolProvider, options, jsonOptions)); }
public NormalController(ArrayPool <char> charPool) { _indentingFormatter = new NewtonsoftJsonOutputFormatter(_indentedSettings, charPool, new MvcOptions(), new MvcNewtonsoftJsonOptions()); }
public IServiceProvider ConfigureServices(IServiceCollection services) { try { services.AddMvc() .AddFluentValidation(fv => fv.RegisterValidatorsFromAssemblyContaining <Startup>()) .AddNewtonsoftJson(options => { options.SerializerSettings.ContractResolver = new DefaultContractResolver(); }); services.Configure <MvcOptions>(options => { options.EnableEndpointRouting = false; }); services.Configure <MvcOptions>(opts => { var serializerSettings = JsonSerializerSettingsProvider.CreateSerializerSettings(); serializerSettings.ContractResolver = new DefaultContractResolver(); serializerSettings.DateFormatString = "yyyy-MM-ddTHH:mm:ss.fffZ"; var jsonOutputFormatter = new NewtonsoftJsonOutputFormatter(serializerSettings, ArrayPool <char> .Create(), opts); opts.OutputFormatters.Insert(0, jsonOutputFormatter); }); services.AddSwaggerGen(options => { options.DefaultLykkeConfiguration(ApiVersion, ApiTitle); options.OperationFilter <ObsoleteOperationFilter>(); options.OperationFilter <SecurityRequirementsOperationFilter>(); options.CustomSchemaIds(type => type.ToString()); options.AddSecurityDefinition("bearer", new OpenApiSecurityScheme { Name = "Authorization", Description = "JWT Authorization header using the Bearer scheme. \r\n\r\n Enter 'Bearer' [space] and then your token in the text input below.\r\n\r\nExample: \"Bearer 12345abcdef\"", In = ParameterLocation.Header, Type = SecuritySchemeType.ApiKey, Scheme = "Bearer", BearerFormat = "JWT" }); }); services.AddSwaggerGenNewtonsoftSupport(); services.AddAuthentication(OAuth2IntrospectionDefaults.AuthenticationScheme) .AddOAuth2Introspection(options => { options.Authority = _appSettings.CurrentValue.WalletApiv2.OAuthSettings.Authority; options.ClientId = _appSettings.CurrentValue.WalletApiv2.OAuthSettings.ClientId; options.ClientSecret = _appSettings.CurrentValue.WalletApiv2.OAuthSettings.ClientSecret; options.NameClaimType = JwtClaimTypes.Subject; options.EnableCaching = true; options.CacheDuration = TimeSpan.FromMinutes(1); options.SkipTokensWithDots = true; }).CustomizeServerAuthentication(); services.Configure <ApiBehaviorOptions>(options => { // Wrap failed model state into LykkeApiErrorResponse. options.InvalidModelStateResponseFactory = InvalidModelStateResponseFactory.CreateInvalidModelResponse; }); var builder = new ContainerBuilder(); Log = CreateLogWithSlack(services, _appSettings); builder.Populate(services); builder.RegisterModule(new Api2Module(_appSettings, Log)); builder.RegisterModule(new ClientsModule(_appSettings, Log)); builder.RegisterModule(new AspNetCoreModule()); builder.RegisterModule(new CqrsModule(_appSettings.CurrentValue, Log)); builder.RegisterModule(new RepositoriesModule(_appSettings.Nested(x => x.WalletApiv2.Db), Log)); ApplicationContainer = builder.Build(); return(new AutofacServiceProvider(ApplicationContainer)); } catch (Exception ex) { Log?.WriteFatalError(nameof(Startup), nameof(ConfigureServices), ex); throw; } }
public FallbackOnTypeBasedMatchController(IOptions <MvcOptions> mvcOptions) { _mvcOptions = mvcOptions; _jsonOutputFormatter = mvcOptions.Value.OutputFormatters.OfType <NewtonsoftJsonOutputFormatter>().First(); }
public JsonFormatterController(ArrayPool <char> charPool) { _indentingFormatter = new NewtonsoftJsonOutputFormatter(_indentedSettings, charPool); }