Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Removed newtonsoft and made serialization agnostic via interface #26

Open
wants to merge 1 commit into
base: develop
Choose a base branch
from
Open
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
2 changes: 2 additions & 0 deletions src/Demo/Demo.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@
<ItemGroup>
<PackageReference Include="FluentValidation.AspNetCore" Version="11.3.0" />
<PackageReference Include="MicroElements.Swashbuckle.FluentValidation" Version="6.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="8.0.11" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="Swashbuckle.AspNetCore.SwaggerGen" Version="7.0.0" />
<PackageReference Include="Swashbuckle.AspNetCore.SwaggerUI" Version="7.0.0" />
</ItemGroup>
Expand Down
32 changes: 32 additions & 0 deletions src/Demo/NewtonsoftSerializationProvider.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using Swashbuckle.AspNetCore.JsonMultipartFormDataSupport.Integrations;

namespace Demo;

public class NewtonsoftSerializationProvider : IMultipartJsonSerializationProvider
{
private readonly JsonSerializerSettings _serializerSettings;

public NewtonsoftSerializationProvider(IOptions<MvcNewtonsoftJsonOptions> options)
{
_serializerSettings = options.Value.SerializerSettings;
}

public NewtonsoftSerializationProvider()
{
_serializerSettings = new MvcNewtonsoftJsonOptions().SerializerSettings;
}

public string Serialize(object value)
{
return JsonConvert.SerializeObject(value, _serializerSettings);
}

public object Deserialize(ModelBindingContext bindingContext, string valueAsString)
{
return JsonConvert.DeserializeObject(valueAsString, bindingContext.ModelType, _serializerSettings)!;
}
}
9 changes: 5 additions & 4 deletions src/Demo/Program.cs
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
using System.Xml;
using Demo;
using Demo.Models.Products;
using FluentValidation;
using FluentValidation.AspNetCore;
using MicroElements.Swashbuckle.FluentValidation.AspNetCore;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Swashbuckle.AspNetCore.Filters;
using Swashbuckle.AspNetCore.JsonMultipartFormDataSupport.Extensions;
using Swashbuckle.AspNetCore.JsonMultipartFormDataSupport.Integrations;
using Formatting=Newtonsoft.Json.Formatting;

var builder = WebApplication.CreateBuilder(args);

Expand All @@ -30,7 +31,7 @@
builder.Services.AddFluentValidationClientsideAdapters();
builder.Services.AddValidatorsFromAssemblyContaining<ProductValidator>();
ValidatorOptions.Global.LanguageManager.Enabled = false;
builder.Services.AddJsonMultipartFormDataSupport(JsonSerializerChoice.Newtonsoft);
builder.Services.AddJsonMultipartFormDataSupport<NewtonsoftSerializationProvider>();
builder.Services.AddSwaggerExamplesFromAssemblyOf<ProductExamples>();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
Expand Down
2 changes: 2 additions & 0 deletions src/DemoOld/DemoOld.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
<ItemGroup>
<PackageReference Include="FluentValidation.AspNetCore" Version="11.3.0" />
<PackageReference Include="MicroElements.Swashbuckle.FluentValidation" Version="6.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="8.0.11" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="Swashbuckle.AspNetCore.SwaggerGen" Version="7.0.0" />
<PackageReference Include="Swashbuckle.AspNetCore.SwaggerUI" Version="7.0.0" />
</ItemGroup>
Expand Down
33 changes: 33 additions & 0 deletions src/DemoOld/NewtonsoftSerializationProvider.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
using System;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using Swashbuckle.AspNetCore.JsonMultipartFormDataSupport.Integrations;

namespace DemoOld;

public class NewtonsoftSerializationProvider : IMultipartJsonSerializationProvider
{
private readonly JsonSerializerSettings _serializerSettings;

public NewtonsoftSerializationProvider(IOptions<MvcNewtonsoftJsonOptions> options)
{
_serializerSettings = options.Value.SerializerSettings;
}

public NewtonsoftSerializationProvider()
{
_serializerSettings = new MvcNewtonsoftJsonOptions().SerializerSettings;
}

public string Serialize(object value)
{
return JsonConvert.SerializeObject(value, _serializerSettings);
}

public object Deserialize(ModelBindingContext bindingContext, string valueAsString)
{
return JsonConvert.DeserializeObject(valueAsString, bindingContext.ModelType, _serializerSettings)!;
}
}
110 changes: 55 additions & 55 deletions src/DemoOld/Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,72 +11,72 @@
using Newtonsoft.Json.Converters;
using Swashbuckle.AspNetCore.Filters;
using Swashbuckle.AspNetCore.JsonMultipartFormDataSupport.Extensions;
using Swashbuckle.AspNetCore.JsonMultipartFormDataSupport.Integrations;

namespace DemoOld {
public class Startup {
public Startup(IConfiguration configuration) {
Configuration = configuration;
}
namespace DemoOld;

public class Startup {
public Startup(IConfiguration configuration) {
Configuration = configuration;
}

public IConfiguration Configuration { get; }
public IConfiguration Configuration { get; }

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services) {
// ===== System.Text.Json =====
// services.AddControllers()
// .AddJsonOptions(options => {
// options.JsonSerializerOptions.WriteIndented = true;
// options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
// });
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services) {
// ===== System.Text.Json =====
// services.AddControllers()
// .AddJsonOptions(options => {
// options.JsonSerializerOptions.WriteIndented = true;
// options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
// });

// ===== JSON.Net- =====
services.AddControllers()
.AddNewtonsoftJson(options => {
options.SerializerSettings.Converters.Add(new StringEnumConverter());
options.SerializerSettings.Formatting = Formatting.Indented;
})
.AddFluentValidation(f => {
f.RegisterValidatorsFromAssemblyContaining<ProductValidator>();
// Important! Without this it won't work automatically
// vvv
f.ImplicitlyValidateChildProperties = true;
// ===== JSON.Net- =====
services.AddControllers()
.AddNewtonsoftJson(options => {
options.SerializerSettings.Converters.Add(new StringEnumConverter());
options.SerializerSettings.Formatting = Formatting.Indented;
})
.AddFluentValidation(f => {
f.RegisterValidatorsFromAssemblyContaining<ProductValidator>();
// Important! Without this it won't work automatically
// vvv
f.ImplicitlyValidateChildProperties = true;

f.LocalizationEnabled = false;
});
f.LocalizationEnabled = false;
});

services.AddJsonMultipartFormDataSupport(JsonSerializerChoice.Newtonsoft);
services.AddSwaggerExamplesFromAssemblyOf<ProductExamples>();
services.AddSwaggerGen(o => {
o.SwaggerDoc("v1", new OpenApiInfo {
Title = "DemoOld",
Version = "v1"
});
// services.AddSingleton<FormDataJsonBinderProvider<NewtonsoftJsonModelBinder>>(sp => new(new(sp.GetRequiredService<IOptions<MvcNewtonsoftJsonOptions>>())));
services.AddJsonMultipartFormDataSupport<NewtonsoftSerializationProvider>();
services.AddSwaggerExamplesFromAssemblyOf<ProductExamples>();
services.AddSwaggerGen(o => {
o.SwaggerDoc("v1", new OpenApiInfo {
Title = "DemoOld",
Version = "v1"
});
services.AddFluentValidationRulesToSwagger();
}
});
services.AddFluentValidationRulesToSwagger();
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) {
if (env.IsDevelopment()) {
app.UseDeveloperExceptionPage();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) {
if (env.IsDevelopment()) {
app.UseDeveloperExceptionPage();
}

app.UseSwagger();
app.UseSwaggerUI(o => {
o.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
o.RoutePrefix = string.Empty;
});
app.UseSwagger();
app.UseSwaggerUI(o => {
o.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
o.RoutePrefix = string.Empty;
});

app.UseHttpsRedirection();
app.UseHttpsRedirection();

app.UseRouting();
app.UseRouting();

app.UseAuthorization();
app.UseAuthorization();

app.UseEndpoints(endpoints => {
endpoints.MapControllers();
});
}
app.UseEndpoints(endpoints => {
endpoints.MapControllers();
});
}
}
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,4 @@
using System;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.DependencyInjection;
using Swashbuckle.AspNetCore.JsonMultipartFormDataSupport.Integrations;

namespace Swashbuckle.AspNetCore.JsonMultipartFormDataSupport.Extensions {
Expand All @@ -12,27 +9,27 @@ public static class MultipartFromDataServicesExtension {
/// <summary>
/// Adds support for json in multipart/form-data requests
/// </summary>
public static IServiceCollection AddJsonMultipartFormDataSupport(this IServiceCollection services, JsonSerializerChoice jsonSerializerChoice) {
JsonMultipartFormDataOptions.JsonSerializerChoice = jsonSerializerChoice;

switch (jsonSerializerChoice) {
case JsonSerializerChoice.SystemText:
services.AddMvc(options => {
var jsonOptions = services.BuildServiceProvider().GetRequiredService<IOptions<JsonOptions>>();
options.ModelBinderProviders.Insert(0, new FormDataJsonBinderProvider(jsonOptions));
});
break;
case JsonSerializerChoice.Newtonsoft:
services.AddMvc(options => {
var jsonOptions = services.BuildServiceProvider().GetRequiredService<IOptions<MvcNewtonsoftJsonOptions>>();
options.ModelBinderProviders.Insert(0, new FormDataJsonBinderProvider(jsonOptions));
});
break;
default:
throw new ArgumentOutOfRangeException(nameof(jsonSerializerChoice), jsonSerializerChoice, null);
}

public static IServiceCollection AddJsonMultipartFormDataSupport<TMultipartJsonSerializationProvider>(this IServiceCollection services)
where TMultipartJsonSerializationProvider : class, IMultipartJsonSerializationProvider
{
services.AddSingleton<IMultipartJsonSerializationProvider, TMultipartJsonSerializationProvider>();

return AddJsonMultipartFormDataSupport(services);
}

/// <summary>
/// Adds support for json in multipart/form-data requests
/// </summary>
public static IServiceCollection AddJsonMultipartFormDataSupport(this IServiceCollection services)
{
var serviceProvider = services.BuildServiceProvider();

var serializationProvider = serviceProvider.GetRequiredService<IMultipartJsonSerializationProvider>();

services.AddMvc(options =>
{
options.ModelBinderProviders.Insert(0, new FormDataJsonBinderProvider(new(serializationProvider)));
});

services.AddSwaggerGen(options => {
options.OperationFilter<MultiPartJsonOperationFilter>();
Expand Down
Original file line number Diff line number Diff line change
@@ -1,28 +1,21 @@
using System;
using System.Reflection;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.Extensions.Options;
using Swashbuckle.AspNetCore.JsonMultipartFormDataSupport.Attributes;

namespace Swashbuckle.AspNetCore.JsonMultipartFormDataSupport.Integrations {
/// <summary>
/// Looks for field with <see cref="FromJsonAttribute"/> and use <see cref="JsonModelBinder"/> for binder.
/// </summary>
public class FormDataJsonBinderProvider : IModelBinderProvider {
private readonly IOptions<JsonOptions> _jsonOptions;
private readonly IOptions<MvcNewtonsoftJsonOptions> _newtonSoftJsonOptions;
readonly JsonModelBinder _jsonModelBinder;

public FormDataJsonBinderProvider(IOptions<JsonOptions> jsonOptions) {
_jsonOptions = jsonOptions;
public FormDataJsonBinderProvider(JsonModelBinder jsonModelBinder)
{
_jsonModelBinder = jsonModelBinder;
}


public FormDataJsonBinderProvider(IOptions<MvcNewtonsoftJsonOptions> newtonSoftJsonOptions) {
_newtonSoftJsonOptions = newtonSoftJsonOptions;
}


/// <inheritdoc />
public IModelBinder GetBinder(ModelBinderProviderContext context) {
if (context == null) throw new ArgumentNullException(nameof(context));
Expand All @@ -42,13 +35,7 @@ public IModelBinder GetBinder(ModelBinderProviderContext context) {
// Do not use this provider if this property does not have the From attribute
if (propInfo.GetCustomAttribute<FromJsonAttribute>() == null) return null;

// All criteria met; use the FormDataJsonBinder
if (_jsonOptions != null)
return new JsonModelBinder(_jsonOptions);
else if (_newtonSoftJsonOptions != null)
return new JsonModelBinder(_newtonSoftJsonOptions);
else
return new JsonModelBinder();
return _jsonModelBinder;
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
using Microsoft.AspNetCore.Mvc.ModelBinding;

namespace Swashbuckle.AspNetCore.JsonMultipartFormDataSupport.Integrations;

/// <summary>
/// Serialization provider for <see cref="JsonModelBinder"/> and <see cref="MultiPartJsonOperationFilter"/>.
/// </summary>
public interface IMultipartJsonSerializationProvider
{
public object Deserialize(ModelBindingContext bindingContext, string valueAsString);
public string Serialize(object value);
}
Loading