Skip to content

Commit

Permalink
pr-fix: deprecate unnecessary extension
Browse files Browse the repository at this point in the history
  • Loading branch information
stijnmoreels committed Oct 10, 2023
1 parent ab04045 commit 161dfcd
Show file tree
Hide file tree
Showing 6 changed files with 11 additions and 111 deletions.
50 changes: 0 additions & 50 deletions docs/preview/03-Features/hosting/formatting-azure-functions.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,54 +33,4 @@ using Microsoft.Extensions.Hosting;
builder.UseOnlyJsonFormatting();
})
.Build();
```

## Configure JSON format
We have provided an extension that will allow you to configure a [`JsonObjectSerializer`](https://learn.microsoft.com/en-us/dotnet/api/azure.core.serialization.jsonobjectserializer?view=azure-dotnet) which will be registered in the application services. This JSON serializer can be injected in your Azure Function implementation so that incoming and outgoing models are handled the same way, across multiple functions.
This makes the JSON formatting more centralized and easier to maintain.

Following example shows you how you can configure these options:

```csharp
using System.Text.Json;
using Microsoft.Extensions.Hosting;

IHost host = new HostBuilder()
.ConfigureFunctionsWorkerDefaults(builder =>
{
builder.ConfigureJsonFormatting(options =>
{
options.Converters.Add(new JsonStringEnumConverter());
});
})
.Build();
```

After that, the `JsonObjectSerializer` can be injected in your function for deserialization/serialization of incoming/outgoing models:

```csharp
using Azure.Core.Serialization;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Azure.Functions.Worker.Http;

public class OrderFunction
{
private readonly JsonObjectSerializer _jsonSerializer;

public OrderFunction(JsonObjectSerializer jsonSerializer)
{
_jsonSerializer = jsonSerializer;
}

[Function("order-processing")]
public async Task<HttpResponseData> Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "post")] HttpRequestData request)
{
var order = await request.ReadFromJsonAsync<Order>(_jsonSerializer);

HttpResponseData response = request.CreateResponse();
await response.WriteAsJsonAsync(order, _jsonSerializer);
return response;
}
}
```
22 changes: 0 additions & 22 deletions docs/preview/03-Features/hosting/formatting.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,25 +30,3 @@ builder.Services.AddControllers(mvcOptions =>
mvcOptions.OnlyAllowJsonFormatting();
});
```

## Configure JSON format
We have provided an extension that will allow you to configure the input and output JSON formatting in one go. This means that any options you configure in this extension will automatically apply to the incoming model as well as the outgoing model. This makes the JSON formatting more streamlined and easier to maintain.

Following example shows you how you can configure these options:

```csharp
using System.Text.Json.Serialization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Mvc;

WebApplicationBuilder builder = WebApplication.CreateBuilder();

builder.Services.AddControllers(mvcOptions =>
{
mvcOptions.ConfigureJsonFormatting(jsonOptions =>
{
jsonOptions.Converters.Add(new JsonStringEnumConverter());
});
});
```

Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using System.Text.Json;
using GuardNet;
using Microsoft.AspNetCore.Mvc.Formatters;
using Microsoft.Extensions.DependencyInjection;

// ReSharper disable once CheckNamespace
namespace Microsoft.AspNetCore.Mvc
Expand Down Expand Up @@ -35,18 +36,19 @@ public static MvcOptions OnlyAllowJsonFormatting(this MvcOptions options)

return options;
}

/// <summary>
/// Configure the MVC JSON formatters for both receiving and sending.
/// </summary>
/// <param name="options">The MVC options where the JSON formatters will be configured.</param>
/// <param name="configureOptions">The function to configure the input and output JSON formatters in the MVC <paramref name="options"/>.</param>
/// <exception cref="ArgumentNullException">Thrown when the <paramref name="options"/> or <paramref name="configureOptions"/> is <c>null</c>.</exception>
[Obsolete("Use the " + nameof(MvcCoreMvcBuilderExtensions) + "." + nameof(MvcCoreMvcBuilderExtensions.AddJsonOptions) + " instead to configure the JSON formatters")]
public static MvcOptions ConfigureJsonFormatting(this MvcOptions options, Action<JsonSerializerOptions> configureOptions)
{
Guard.NotNull(options, nameof(options), "Requires MVC options to configure the JSON formatters");
Guard.NotNull(configureOptions, nameof(configureOptions), "Requires a function to configure the JSON formatters in the MVC options");

SystemTextJsonInputFormatter[] onlyJsonInputFormatters =
options.InputFormatters.OfType<SystemTextJsonInputFormatter>()
.ToArray();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -129,10 +129,7 @@ public async Task IncomingModel_WithoutConfigureJsonFormattingOnEnums_Serializes
{
// Arrange
var options = new TestApiServerOptions()
.ConfigureServices(services => services.AddMvc(mvcOptions =>
{
mvcOptions.ConfigureJsonFormatting(jsonOptions => { });
}));
.ConfigureServices(services => services.AddMvc());

var country = new Country
{
Expand Down Expand Up @@ -164,10 +161,11 @@ public async Task IncomingModel_WithConfigureJsonFormattingOnEnums_SerializeAsSt
{
// Arrange
var options = new TestApiServerOptions()
.ConfigureServices(services => services.AddMvc(mvcOptions =>
.ConfigureServices(services =>
{
mvcOptions.ConfigureJsonFormatting(jsonOptions => jsonOptions.Converters.Add(new JsonStringEnumConverter()));
}));
services.AddMvc()
.AddJsonOptions(opt => opt.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter()));
});

var country = new Country
{
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using System.Collections.Generic;
using System.Text.Json;
using Bogus;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Formatters;
Expand Down Expand Up @@ -37,35 +36,6 @@ public void OnlyAllowJsonFormatting_WithDefault_ConfiguresFormatters()
Assert.Empty(options.OutputFormatters);
}

[Fact]
public void ConfigureJsonFormatting_WithOptions_ConfiguresFormatters()
{
// Arrange
var options = new MvcOptions();
IEnumerable<SystemTextJsonInputFormatter> inputFormatters =
CreateRandomSubset(new SystemTextJsonInputFormatter(new JsonOptions(), NullLogger<SystemTextJsonInputFormatter>.Instance));
Assert.All(inputFormatters, formatter => options.InputFormatters.Add(formatter));
IEnumerable<SystemTextJsonOutputFormatter> outputFormatters =
CreateRandomSubset(new SystemTextJsonOutputFormatter(new JsonSerializerOptions()));
Assert.All(outputFormatters, formatter => options.OutputFormatters.Add(formatter));
bool allowTrailingCommas = BogusGenerator.Random.Bool();

// Act
options.ConfigureJsonFormatting(opt => opt.AllowTrailingCommas = allowTrailingCommas);

// Assert
Assert.All(options.InputFormatters, formatter =>
{
var jsonFormatter = Assert.IsType<SystemTextJsonInputFormatter>(formatter);
Assert.Equal(allowTrailingCommas, jsonFormatter.SerializerOptions.AllowTrailingCommas);
});
Assert.All(options.OutputFormatters, formatter =>
{
var jsonFormatter = Assert.IsType<SystemTextJsonOutputFormatter>(formatter);
Assert.Equal(allowTrailingCommas, jsonFormatter.SerializerOptions.AllowTrailingCommas);
});
}

private static IEnumerable<T> CreateRandomSubset<T>(params T[] formatters)
{
int count = BogusGenerator.Random.Int(5, 10);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ public void AddJwtBearer_WithServiceProvider_Succeeds()
services.AddSingleton(Mock.Of<ISystemClock>());

Check warning on line 22 in src/Arcus.WebApi.Tests.Unit/Security/Authentication/AuthenticationBuilderExtensionsTests.cs

View workflow job for this annotation

GitHub Actions / Analyze (csharp)

'ISystemClock' is obsolete: 'Use TimeProvider instead.'

Check warning on line 22 in src/Arcus.WebApi.Tests.Unit/Security/Authentication/AuthenticationBuilderExtensionsTests.cs

View workflow job for this annotation

GitHub Actions / Analyze (csharp)

'ISystemClock' is obsolete: 'Use TimeProvider instead.'
services.AddSingleton(UrlEncoder.Default);
services.AddSecretStore(stores => stores.AddInMemory());
services.AddSingleton(Mock.Of<TimeProvider>());
var builder = new AuthenticationBuilder(services);

// Act
Expand All @@ -47,6 +48,7 @@ public void AddJwtBearer_WithoutOptions_Succeeds()
services.AddLogging();
services.AddSingleton(Mock.Of<ISystemClock>());

Check warning on line 49 in src/Arcus.WebApi.Tests.Unit/Security/Authentication/AuthenticationBuilderExtensionsTests.cs

View workflow job for this annotation

GitHub Actions / Analyze (csharp)

'ISystemClock' is obsolete: 'Use TimeProvider instead.'

Check warning on line 49 in src/Arcus.WebApi.Tests.Unit/Security/Authentication/AuthenticationBuilderExtensionsTests.cs

View workflow job for this annotation

GitHub Actions / Analyze (csharp)

'ISystemClock' is obsolete: 'Use TimeProvider instead.'
services.AddSingleton(UrlEncoder.Default);
services.AddSingleton(Mock.Of<TimeProvider>());
var builder = new AuthenticationBuilder(services);

// Act
Expand Down

0 comments on commit 161dfcd

Please sign in to comment.