Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,27 +1,44 @@
---
uid: Codebelt.Extensions.AspNetCore.Mvc.Formatters.Newtonsoft.Json.JsonSerializationInputFormatter
example:
- *content
---

Create `JsonSerializationInputFormatter` directly when you want to confirm which JSON media types and encodings MVC will accept before the formatter is inserted into `MvcOptions`.

```csharp
// Program.cs
using System;
using System.Linq;
using System.Net.Http.Headers;
using Codebelt.Extensions.AspNetCore.Mvc.Formatters.Newtonsoft.Json;
using Codebelt.Extensions.Newtonsoft.Json.Formatters;

var options = new NewtonsoftJsonFormatterOptions();
options.SupportedMediaTypes = options.SupportedMediaTypes
.Append(MediaTypeHeaderValue.Parse("application/vnd.weather+json"))
.ToArray();

var formatter = new JsonSerializationInputFormatter(options);

Console.WriteLine(formatter.SupportedMediaTypes.Any(mediaType => mediaType == "application/json"));
Console.WriteLine(formatter.SupportedMediaTypes.Any(mediaType => mediaType == "application/vnd.weather+json"));
Console.WriteLine(formatter.SupportedEncodings.Count);
```
---
uid: Codebelt.Extensions.AspNetCore.Mvc.Formatters.Newtonsoft.Json.JsonSerializationInputFormatter
example:
- *content
---

ASP.NET Core MVC model binding automatically deserializes incoming JSON request bodies to controller action parameters, but only when the appropriate input formatter is registered that understands JSON.NET configuration, custom converters, and exception sensitivity rules. Without proper input formatter setup, JSON deserialization defaults to the framework's built-in serializer or misses custom converters registered with Newtonsoft.Json. The `JsonSerializationInputFormatter` class integrates Newtonsoft.Json with ASP.NET Core's formatter pipeline, supporting custom converters, null value handling, and media type negotiation as configured in `NewtonsoftJsonFormatterOptions`. This example demonstrates direct instantiation and usage of the JSON input formatter to deserialize JSON data:

```csharp
using System;
using Codebelt.Extensions.AspNetCore.Mvc.Formatters.Newtonsoft.Json;
using Codebelt.Extensions.Newtonsoft.Json.Formatters;
using Newtonsoft.Json;

namespace Examples;

public class DataModel
{
public string Name { get; set; }
public DateTime CreatedAt { get; set; }
public string[] Tags { get; set; }
}

class JsonSerializationInputFormatterExample
{
static void Main()
{
// Create formatter with custom options
var options = new NewtonsoftJsonFormatterOptions();
var inputFormatter = new JsonSerializationInputFormatter(options);

// The formatter is now registered and ready to handle JSON deserialization
// in an ASP.NET Core MVC application. It integrates with the framework's
// input formatter pipeline to deserialize incoming HTTP request bodies.

var json = @"{""name"":""Test Data"",""createdAt"":""2024-01-01T00:00:00Z"",""tags"":[""important"",""review""]}";
var deserialized = JsonConvert.DeserializeObject<DataModel>(json, options.Settings);

Console.WriteLine($"Deserialized: {deserialized.Name}");
}
}
```

The `JsonSerializationInputFormatter` automatically registers support for multiple JSON media types (`application/json`, `text/json`, and `application/problem+json`) and handles UTF-8 and UTF-16 encodings. The formatter integrates with the configured `NewtonsoftJsonFormatterOptions` to apply custom converters and serialization rules, including HTTP exception descriptor conversion when configured.
Original file line number Diff line number Diff line change
@@ -1,35 +1,59 @@
---
uid: Codebelt.Extensions.AspNetCore.Mvc.Formatters.Newtonsoft.Json.JsonSerializationMvcOptionsSetup
example:
- *content
---

Use `JsonSerializationMvcOptionsSetup` when you want `MvcOptions` to prefer the Newtonsoft.Json formatters first while preserving any later formatters MVC already knows about.

```csharp
// Program.cs
using System;
using System.Linq;
using Codebelt.Extensions.AspNetCore.Mvc.Formatters.Newtonsoft.Json;
using Codebelt.Extensions.Newtonsoft.Json.Formatters;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;

var services = new ServiceCollection();
services.Configure<NewtonsoftJsonFormatterOptions>(options => options.Settings.Formatting = Formatting.None);
services.AddSingleton<IConfigureOptions<MvcOptions>, JsonSerializationMvcOptionsSetup>();

var provider = services.BuildServiceProvider();
var mvcOptions = new MvcOptions();

foreach (var configurator in provider.GetServices<IConfigureOptions<MvcOptions>>())
{
configurator.Configure(mvcOptions);
}

Console.WriteLine(mvcOptions.OutputFormatters[0] is JsonSerializationOutputFormatter);
Console.WriteLine(mvcOptions.InputFormatters[0] is JsonSerializationInputFormatter);
Console.WriteLine(mvcOptions.OutputFormatters.OfType<JsonSerializationOutputFormatter>().Count());
```
---
uid: Codebelt.Extensions.AspNetCore.Mvc.Formatters.Newtonsoft.Json.JsonSerializationMvcOptionsSetup
example:
- *content
---

ASP.NET Core's dependency injection system calls `IConfigureOptions<MvcOptions>` implementations during MVC setup to register formatters and configure behavior, but manually creating and registering these setup classes is verbose and error-prone. The `JsonSerializationMvcOptionsSetup` class encapsulates the work of registering both input and output formatters with consistent Newtonsoft.Json configuration, and when registered via extension methods like `AddMvc()`, it seamlessly integrates formatters into the standard MVC pipeline without requiring developers to handle setup details. This example demonstrates direct instantiation and usage of this `IConfigureOptions<MvcOptions>` implementation:

```csharp
using System;
using System.Linq;
using Codebelt.Extensions.AspNetCore.Mvc.Formatters.Newtonsoft.Json;
using Codebelt.Extensions.Newtonsoft.Json.Formatters;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;

namespace Examples;

class JsonSerializationMvcOptionsSetupExample
{
static void Main()
{
// Create formatter options
var formatterOptions = new NewtonsoftJsonFormatterOptions
{
Settings = new JsonSerializerSettings
{
Formatting = Formatting.Indented,
NullValueHandling = NullValueHandling.Ignore
}
};

// Create MVC options
var mvcOptions = new MvcOptions();

// Create and apply the setup
var setup = new JsonSerializationMvcOptionsSetup(
Options.Create(formatterOptions)
);

// Configure MVC options with the formatters
setup.Configure(mvcOptions);

// Verify formatters were added
Console.WriteLine($"Input formatters count: {mvcOptions.InputFormatters.Count}");
Console.WriteLine($"Output formatters count: {mvcOptions.OutputFormatters.Count}");

// Check if our formatters are present
var hasInputFormatter = mvcOptions.InputFormatters.OfType<JsonSerializationInputFormatter>().Any();
var hasOutputFormatter = mvcOptions.OutputFormatters.OfType<JsonSerializationOutputFormatter>().Any();

Console.WriteLine($"Has JsonSerializationInputFormatter: {hasInputFormatter}");
Console.WriteLine($"Has JsonSerializationOutputFormatter: {hasOutputFormatter}");
}
}
```

The setup automatically inserts both `JsonSerializationInputFormatter` and `JsonSerializationOutputFormatter` at the beginning of the MVC formatters collection, ensuring Newtonsoft.Json is the primary JSON handler for your application.
Original file line number Diff line number Diff line change
@@ -1,27 +1,59 @@
---
uid: Codebelt.Extensions.AspNetCore.Mvc.Formatters.Newtonsoft.Json.JsonSerializationOutputFormatter
example:
- *content
---

Create `JsonSerializationOutputFormatter` directly when you need to inspect the response media types MVC will negotiate after you customize the shared Newtonsoft.Json formatter options.

```csharp
// Program.cs
using System;
using System.Linq;
using System.Net.Http.Headers;
using Codebelt.Extensions.AspNetCore.Mvc.Formatters.Newtonsoft.Json;
using Codebelt.Extensions.Newtonsoft.Json.Formatters;

var options = new NewtonsoftJsonFormatterOptions();
options.SupportedMediaTypes = options.SupportedMediaTypes
.Append(MediaTypeHeaderValue.Parse("application/vnd.invoice+json"))
.ToArray();

var formatter = new JsonSerializationOutputFormatter(options);

Console.WriteLine(formatter.SupportedMediaTypes.Any(mediaType => mediaType == "application/problem+json"));
Console.WriteLine(formatter.SupportedMediaTypes.Any(mediaType => mediaType == "application/vnd.invoice+json"));
Console.WriteLine(formatter.SupportedEncodings.Count);
```
---
uid: Codebelt.Extensions.AspNetCore.Mvc.Formatters.Newtonsoft.Json.JsonSerializationOutputFormatter
example:
- *content
---

ASP.NET Core MVC converts controller action return values to HTTP response bodies using output formatters, but without registering a Newtonsoft.Json-aware formatter, responses use the default System.Text.Json serializer which doesn't know about custom converters, exception descriptors, or exception sensitivity settings configured elsewhere. Objects with complex serialization requirements—exceptions, domain models with custom converters, flag enums—won't serialize correctly unless an output formatter that understands Newtonsoft.Json is available. The `JsonSerializationOutputFormatter` class integrates Newtonsoft.Json serialization into the MVC response pipeline, applying custom converters and settings configured in `NewtonsoftJsonFormatterOptions` to all response objects. This example demonstrates direct instantiation and usage of the JSON output formatter to serialize objects:

```csharp
using System;
using Codebelt.Extensions.AspNetCore.Mvc.Formatters.Newtonsoft.Json;
using Codebelt.Extensions.Newtonsoft.Json.Formatters;
using Newtonsoft.Json;

namespace Examples;

public class WeatherForecast
{
public DateTime Date { get; set; }
public int Temperature { get; set; }
public string Summary { get; set; }
public string Location { get; set; }
}

class JsonSerializationOutputFormatterExample
{
static void Main()
{
// Create formatter with custom options
var options = new NewtonsoftJsonFormatterOptions
{
Settings = new JsonSerializerSettings
{
Formatting = Formatting.Indented,
NullValueHandling = NullValueHandling.Ignore
}
};

var outputFormatter = new JsonSerializationOutputFormatter(options);

// Create object to serialize
var forecast = new WeatherForecast
{
Date = DateTime.Now,
Temperature = 25,
Summary = "Warm",
Location = "Seattle"
};

// The formatter is now registered and ready to handle JSON serialization
// in an ASP.NET Core MVC application response pipeline
var json = JsonConvert.SerializeObject(forecast, options.Settings);
Console.WriteLine("Serialized WeatherForecast:");
Console.WriteLine(json);
}
}
```

The `JsonSerializationOutputFormatter` respects the formatter options and applies custom converters such as exception descriptor converters when serializing response objects. It supports the same media types as the input formatter and automatically handles content negotiation.
Loading
Loading