This commit is contained in:
2026-03-25 14:55:34 +08:00
commit 2c44b3a4b2
131 changed files with 7453 additions and 0 deletions

View File

@@ -0,0 +1,79 @@
using System.Text.Json.Serialization;
using StopShopping.Api.Middlewares;
using StopShopping.Services;
using StopShopping.Services.Extensions;
namespace StopShopping.Api.Extensions;
public static class CommonServiceCollections
{
public static IServiceCollection AddCommonServices(
this IServiceCollection services,
string corsPolicy,
IConfigurationSection jwtConfiguration,
IConfigurationSection appConfiguration,
bool isDevelopment)
{
var appOptions = appConfiguration.Get<AppOptions>();
services.AddCors(options =>
{
options.AddPolicy(corsPolicy, policy =>
{
policy.AllowAnyHeader();
policy.AllowAnyMethod();
policy.WithOrigins(appOptions!.CorsAllowedOrigins);
policy.AllowCredentials();
});
});
services.ConfigureHttpJsonOptions(options =>
{
options.SerializerOptions.Converters.Add(
new JsonStringEnumConverter(namingPolicy: null, allowIntegerValues: true));
});
services.AddHttpContextAccessor();
services.AddOpenApi(options =>
{
options.AddDocumentTransformer<BearerOpenApiDocumentTransformer>();
options.AddSchemaTransformer<EnumOpenApiSchemaTransformer>();
});
services.AddProblemDetails(options =>
{
options.CustomizeProblemDetails = (context) =>
{
if (context.ProblemDetails is HttpValidationProblemDetails problemDetails)
{
problemDetails.AddErrorCode(ProblemDetailsCodes.ParametersValidationFailed);
var errors = problemDetails.Errors.Select(e => string.Join(',', e.Value));
if (null != errors)
problemDetails.Detail = string.Join(',', errors);
}
};
});
services.AddValidation();
services.AddDistributedMemoryCache();
services.AddAuthServices(jwtConfiguration);
services.AddAntiforgery(options =>
{
var jwtOptions = jwtConfiguration.Get<JwtOptions>();
options.HeaderName = appOptions!.CSRFHeaderName;
options.Cookie.MaxAge = TimeSpan.FromSeconds(jwtOptions!.RefreshTokenExpiresIn);
options.Cookie.HttpOnly = true;
options.Cookie.Name = appOptions.CSRFCookieName;
if (isDevelopment)
{
options.Cookie.SameSite = SameSiteMode.Lax;
}
else
{
options.Cookie.SameSite = SameSiteMode.None;
options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
options.Cookie.Domain = appOptions.CookieDomain;
}
});
return services;
}
}