Skip to content

Open-source eCommerce platform for C# and ASP.NET Core 10 with MongoDB. Build multi-store shops and multi-vendor marketplaces with B2B/B2C, REST API, plugins, Vue 3 and Docker.

Frontent API - improved, add new settings FrontendAPIConfig.JsonContentType

support708d47ba5d1d
diff --git a/src/Core/Grand.Infrastructure/Configuration/FrontendAPIConfig.cs b/src/Core/Grand.Infrastructure/Configuration/FrontendAPIConfig.cs
index 76369c380..8fae37a7c 100644
--- a/src/Core/Grand.Infrastructure/Configuration/FrontendAPIConfig.cs
+++ b/src/Core/Grand.Infrastructure/Configuration/FrontendAPIConfig.cs
@@ -4,6 +4,7 @@
{
public static string Scheme => "GrandWebBearerScheme";
public bool Enabled { get; set; }
+ public bool JsonContentType { get; set; }
public string SecretKey { get; set; }
public bool ValidateIssuer { get; set; }
public string ValidIssuer { get; set; }
diff --git a/src/Core/Grand.Infrastructure/Extensions/MvcOptionsExtensions.cs b/src/Core/Grand.Infrastructure/Extensions/MvcOptionsExtensions.cs
new file mode 100644
index 000000000..517d287ab
--- /dev/null
+++ b/src/Core/Grand.Infrastructure/Extensions/MvcOptionsExtensions.cs
@@ -0,0 +1,25 @@
+using Grand.Infrastructure.ModelBinding;
+using Microsoft.AspNetCore.Mvc;
+using Microsoft.AspNetCore.Mvc.ModelBinding;
+
+namespace Grand.Infrastructure.Extensions;
+
+public static class MvcOptionsExtensions
+{
+ public static void UseJsonBodyModelBinderProviderInsteadOf<T>(this MvcOptions mvcOptions) where T : IModelBinderProvider
+ {
+ var replacedModelBinderProvider = mvcOptions.ModelBinderProviders.OfType<T>().FirstOrDefault();
+ if (replacedModelBinderProvider == null) return;
+ var pos = 0;
+ for (var i = 0; i < mvcOptions.ModelBinderProviders.Count; i++)
+ {
+ if (mvcOptions.ModelBinderProviders[i] is T)
+ {
+ pos = i;
+ }
+ }
+ var customProvider = new JsonBodyModelBinderProvider(replacedModelBinderProvider);
+ mvcOptions.ModelBinderProviders.Remove(replacedModelBinderProvider);
+ mvcOptions.ModelBinderProviders.Insert(pos, customProvider);
+ }
+}
\ No newline at end of file
diff --git a/src/Core/Grand.Infrastructure/ModelBinding/JsonBodyModelBinder.cs b/src/Core/Grand.Infrastructure/ModelBinding/JsonBodyModelBinder.cs
new file mode 100644
index 000000000..e7abbcf3a
--- /dev/null
+++ b/src/Core/Grand.Infrastructure/ModelBinding/JsonBodyModelBinder.cs
@@ -0,0 +1,48 @@
+using Grand.Infrastructure.TypeConverters.JsonConverters;
+using Microsoft.AspNetCore.Mvc.ModelBinding;
+using System.Text.Json;
+using JsonSerializer = System.Text.Json.JsonSerializer;
+
+namespace Grand.Infrastructure.ModelBinding;
+
+public class JsonBodyModelBinder : IModelBinder
+{
+ private readonly IModelBinder _overriddenModelBinder;
+
+ public JsonBodyModelBinder(IModelBinder overriddenModelBinder)
+ {
+ _overriddenModelBinder = overriddenModelBinder;
+ }
+
+ public async Task BindModelAsync(ModelBindingContext bindingContext)
+ {
+ var httpContext = bindingContext.HttpContext;
+ var hasJsonContentType = httpContext.Request.ContentType?.Contains("application/json") ?? false;
+ if (hasJsonContentType)
+ {
+ try
+ {
+ string jsonPayload;
+ using (var streamReader = new StreamReader(httpContext.Request.Body))
+ {
+ jsonPayload = await streamReader.ReadToEndAsync();
+ }
+ var options = new JsonSerializerOptions
+ {
+ PropertyNameCaseInsensitive = true
+ };
+ options.Converters.Add(new StringConverter());
+ bindingContext.Result =
+ ModelBindingResult.Success(JsonSerializer.Deserialize(jsonPayload, bindingContext.ModelType, options));
+ }
+ catch(Exception exception)
+ {
+ bindingContext.Result = ModelBindingResult.Success(Activator.CreateInstance(bindingContext.ModelType));
+ }
+ }
+ else
+ {
+ await _overriddenModelBinder.BindModelAsync(bindingContext);
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/Core/Grand.Infrastructure/ModelBinding/JsonBodyModelBinderProvider.cs b/src/Core/Grand.Infrastructure/ModelBinding/JsonBodyModelBinderProvider.cs
new file mode 100644
index 000000000..ffeeed4b2
--- /dev/null
+++ b/src/Core/Grand.Infrastructure/ModelBinding/JsonBodyModelBinderProvider.cs
@@ -0,0 +1,17 @@
+using Microsoft.AspNetCore.Mvc.ModelBinding;
+
+namespace Grand.Infrastructure.ModelBinding;
+
+public class JsonBodyModelBinderProvider : IModelBinderProvider
+{
+ private readonly IModelBinderProvider _overriddenModelBinderProvider;
+ public JsonBodyModelBinderProvider(IModelBinderProvider overriddenModelBinderProvider)
+ {
+ _overriddenModelBinderProvider = overriddenModelBinderProvider;
+ }
+ public IModelBinder GetBinder(ModelBinderProviderContext context)
+ {
+ var modelBinder = _overriddenModelBinderProvider.GetBinder(context);
+ return modelBinder == null ? null : new JsonBodyModelBinder(modelBinder);
+ }
+}
\ No newline at end of file
diff --git a/src/Core/Grand.Infrastructure/StartupBase.cs b/src/Core/Grand.Infrastructure/StartupBase.cs
index a062bcdb8..bf3a6c351 100644
--- a/src/Core/Grand.Infrastructure/StartupBase.cs
+++ b/src/Core/Grand.Infrastructure/StartupBase.cs
@@ -2,6 +2,7 @@
using Grand.Domain.Data;
using Grand.Infrastructure.Caching.RabbitMq;
using Grand.Infrastructure.Configuration;
+using Grand.Infrastructure.Extensions;
using Grand.Infrastructure.Mapper;
using Grand.Infrastructure.Plugins;
using Grand.Infrastructure.Roslyn;
@@ -16,6 +17,7 @@ using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Infrastructure;
+using Microsoft.AspNetCore.Mvc.ModelBinding.Binders;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
@@ -100,9 +102,10 @@ namespace Grand.Infrastructure
.AddClasses(classes => classes.AssignableTo(typeof(IValidatorConsumer<>)))
.AsImplementedInterfaces().WithScopedLifetime());
}
-
-
- private static T StartupConfig<T>(this IServiceCollection services, IConfiguration configuration) where T : class, new()
+
+
+ private static T StartupConfig<T>(this IServiceCollection services, IConfiguration configuration)
+ where T : class, new()
{
if (services == null)
throw new ArgumentNullException(nameof(services));
@@ -157,7 +160,8 @@ namespace Grand.Infrastructure
/// <param name="services"></param>
/// <param name="configuration"></param>
/// <param name="typeSearcher"></param>
- private static void AddMassTransitRabbitMq(IServiceCollection services, IConfiguration configuration, ITypeSearcher typeSearcher)
+ private static void AddMassTransitRabbitMq(IServiceCollection services, IConfiguration configuration,
+ ITypeSearcher typeSearcher)
{
var config = new RabbitConfig();
configuration.GetSection("Rabbit").Bind(config);
@@ -169,7 +173,8 @@ namespace Grand.Infrastructure
if (config.RabbitCachePubSubEnabled)
{
- x.AddConsumer<CacheMessageEventConsumer>().Endpoint(t => t.Name = config.RabbitCacheReceiveEndpoint);
+ x.AddConsumer<CacheMessageEventConsumer>()
+ .Endpoint(t => t.Name = config.RabbitCacheReceiveEndpoint);
}
x.UsingRabbitMq((context, cfg) =>
@@ -220,7 +225,8 @@ namespace Grand.Infrastructure
CommonPath.WebHostEnvironment = hostingEnvironment.WebRootPath;
CommonPath.BaseDirectory = hostingEnvironment.ContentRootPath;
CommonHelper.CacheTimeMinutes = performanceConfig.DefaultCacheTimeMinutes;
- CommonHelper.CookieAuthExpires = securityConfig.CookieAuthExpires > 0 ? securityConfig.CookieAuthExpires : 24 * 365;
+ CommonHelper.CookieAuthExpires =
+ securityConfig.CookieAuthExpires > 0 ? securityConfig.CookieAuthExpires : 24 * 365;
CommonHelper.IgnoreAcl = performanceConfig.IgnoreAcl;
CommonHelper.IgnoreStoreLimitations = performanceConfig.IgnoreStoreLimitations;
@@ -229,6 +235,13 @@ namespace Grand.Infrastructure
var mvcCoreBuilder = services.AddMvcCore(options =>
{
options.Filters.AddService<FluentValidationFilter>();
+ var frontConfig = new FrontendAPIConfig();
+ configuration.GetSection("FrontendAPI").Bind(frontConfig);
+ if (frontConfig.JsonContentType)
+ {
+ options.UseJsonBodyModelBinderProviderInsteadOf<DictionaryModelBinderProvider>();
+ options.UseJsonBodyModelBinderProviderInsteadOf<ComplexObjectModelBinderProvider>();
+ }
});
return mvcCoreBuilder;
@@ -239,7 +252,6 @@ namespace Grand.Infrastructure
#region Methods
-
/// <summary>
/// Add and configure services
/// </summary>
@@ -278,7 +290,7 @@ namespace Grand.Infrastructure
//Register type validator consumer
RegisterValidatorConsumer(services, typeSearcher);
-
+
//add mediator
AddMediator(services, typeSearcher);
@@ -305,7 +317,8 @@ namespace Grand.Infrastructure
/// </summary>
/// <param name="application">Builder for configuring an application's request pipeline</param>
/// <param name="webHostEnvironment">WebHostEnvironment</param>
- public static void ConfigureRequestPipeline(IApplicationBuilder application, IWebHostEnvironment webHostEnvironment)
+ public static void ConfigureRequestPipeline(IApplicationBuilder application,
+ IWebHostEnvironment webHostEnvironment)
{
//find startup configurations provided by other assemblies
var typeSearcher = new TypeSearcher();
@@ -337,6 +350,5 @@ namespace Grand.Infrastructure
}
#endregion
-
}
-}
+}
\ No newline at end of file
diff --git a/src/Core/Grand.Infrastructure/TypeConverters/JsonConverters/StringConverter.cs b/src/Core/Grand.Infrastructure/TypeConverters/JsonConverters/StringConverter.cs
new file mode 100644
index 000000000..8b4dfb37a
--- /dev/null
+++ b/src/Core/Grand.Infrastructure/TypeConverters/JsonConverters/StringConverter.cs
@@ -0,0 +1,32 @@
+using System.Text.Json;
+
+namespace Grand.Infrastructure.TypeConverters.JsonConverters;
+
+public class StringConverter : System.Text.Json.Serialization.JsonConverter<string>
+{
+ public override string Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
+ {
+ switch (reader.TokenType)
+ {
+ case JsonTokenType.Number:
+ {
+ var stringValue = reader.GetInt32();
+ return stringValue.ToString();
+ }
+ case JsonTokenType.True:
+ return "true";
+ case JsonTokenType.False:
+ return "false";
+ case JsonTokenType.String:
+ return reader.GetString();
+ default:
+ throw new System.Text.Json.JsonException();
+ }
+ }
+
+ public override void Write(Utf8JsonWriter writer, string value, JsonSerializerOptions options)
+ {
+ writer.WriteStringValue(value);
+ }
+
+}
\ No newline at end of file
diff --git a/src/Core/Grand.Infrastructure/Validators/FluentValidationFilter.cs b/src/Core/Grand.Infrastructure/Validators/FluentValidationFilter.cs
index 4934772ba..c4b102e19 100644
--- a/src/Core/Grand.Infrastructure/Validators/FluentValidationFilter.cs
+++ b/src/Core/Grand.Infrastructure/Validators/FluentValidationFilter.cs
@@ -1,6 +1,7 @@
using FluentValidation;
using FluentValidation.AspNetCore;
using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
namespace Grand.Infrastructure.Validators
@@ -46,7 +47,16 @@ namespace Grand.Infrastructure.Validators
{
var contextValidator = new ValidationContext<object>(model);
var result = await validator.ValidateAsync(contextValidator);
- if (!result.IsValid) result.AddToModelState(context.ModelState, "");
+ if (!result.IsValid)
+ {
+ result.AddToModelState(context.ModelState, "");
+ var hasJsonData = context.HttpContext.Request.ContentType?.Contains("application/json") ?? false;
+ if (hasJsonData)
+ {
+ context.Result = new BadRequestObjectResult(context.ModelState);
+ return;
+ }
+ }
}
}
diff --git a/src/Web/Grand.Web/App_Data/appsettings.json b/src/Web/Grand.Web/App_Data/appsettings.json
index c386abd68..4e7256589 100644
--- a/src/Web/Grand.Web/App_Data/appsettings.json
+++ b/src/Web/Grand.Web/App_Data/appsettings.json
@@ -222,6 +222,7 @@
//access to the api to web controllers
"FrontendAPI": {
"Enabled": false,
+ "JsonContentType": false, //when is enabled, use ContentType = application/json to read json from body, default is form-data
"SecretKey": "your private secret key", //at least 16 characters
"ValidateIssuer": false,
"ValidIssuer": "",