mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-03 13:11:10 +00:00
Adds localization to Lumina.Presentation.Web project
This commit is contained in:
1 parent
771fa74991
commit
2c31fd8714
65 files changed
+1111
-319
No files matched your search
@@ -37,7 +37,7 @@ public class InitializationHandler : AuthorizationHandler<InitializationRequirem
|
||||
/// <param name="requirement">The initialization requirement to be evaluated.</param>
|
||||
protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, InitializationRequirement requirement)
|
||||
{
|
||||
InitializationModel result = await _apiHttpClient.GetAsync<InitializationModel>("initialization/");
|
||||
InitializationModel result = await _apiHttpClient.GetAsync<InitializationModel>("initialization/").ConfigureAwait(false);
|
||||
HttpContext? httpContext = context.Resource as HttpContext;
|
||||
if (result.IsInitialized)
|
||||
{
|
||||
|
||||
+109
-35
@@ -4,6 +4,7 @@ using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.Authorization;
|
||||
using Lumina.Presentation.Web.Common.Exceptions;
|
||||
using Lumina.Presentation.Web.Common.Filters;
|
||||
using Lumina.Presentation.Web.Common.MiddlewareFilters;
|
||||
using Lumina.Presentation.Web.Common.Security;
|
||||
using Lumina.Presentation.Web.Common.Services;
|
||||
using Microsoft.AspNetCore.Authentication.Cookies;
|
||||
@@ -11,6 +12,10 @@ using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.HttpOverrides;
|
||||
using Microsoft.AspNetCore.Localization;
|
||||
using Microsoft.AspNetCore.Localization.Routing;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Mvc.Razor;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Polly;
|
||||
using Polly.CircuitBreaker;
|
||||
@@ -18,6 +23,7 @@ using Polly.Retry;
|
||||
using Polly.Wrap;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Globalization;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json.Serialization;
|
||||
@@ -39,49 +45,117 @@ public static class PresentationWebLayerServices
|
||||
/// <returns>The updated <see cref="IServiceCollection"/>.</returns>
|
||||
public static IServiceCollection AddPresentationWebLayerServices(this IServiceCollection services)
|
||||
{
|
||||
services.AddControllersWithViews(options => options.Filters.Add(typeof(ApiExceptionFilter)))
|
||||
.AddJsonOptions(options =>
|
||||
services.AddControllersWithViews(mvcOptions =>
|
||||
{
|
||||
mvcOptions.Filters.Add<ApiExceptionFilter>();
|
||||
mvcOptions.Filters.Add(new MiddlewareFilterAttribute(typeof(LocalizationPipeline))); // add localization middleware filter
|
||||
})
|
||||
.AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
|
||||
.AddDataAnnotationsLocalization()
|
||||
.AddJsonOptions(jsonOptions =>
|
||||
{
|
||||
jsonOptions.JsonSerializerOptions.MaxDepth = 256;
|
||||
jsonOptions.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles; // needed because file system API responses can have very nested structures
|
||||
jsonOptions.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
|
||||
});
|
||||
// configure URL-based localization
|
||||
services.AddLocalization(localizationOptions =>
|
||||
{
|
||||
localizationOptions.ResourcesPath = "Resources";
|
||||
});
|
||||
|
||||
services.Configure<RequestLocalizationOptions>(requestLocalizationOptions =>
|
||||
{
|
||||
CultureInfo[] supportedCultures =
|
||||
[
|
||||
new CultureInfo("de-DE"),
|
||||
new CultureInfo("en-US"),
|
||||
new CultureInfo("es-ES"),
|
||||
new CultureInfo("fr-FR"),
|
||||
new CultureInfo("it-IT"),
|
||||
new CultureInfo("ja-JP"),
|
||||
new CultureInfo("ro-RO"),
|
||||
new CultureInfo("ru-RU"),
|
||||
new CultureInfo("zh-CN"),
|
||||
];
|
||||
requestLocalizationOptions.DefaultRequestCulture = new RequestCulture("en-US");
|
||||
requestLocalizationOptions.SupportedCultures = supportedCultures;
|
||||
requestLocalizationOptions.SupportedUICultures = supportedCultures;
|
||||
|
||||
// configure route-based culture provider
|
||||
RouteDataRequestCultureProvider routeDataRequestCultureProvider = new()
|
||||
{
|
||||
options.JsonSerializerOptions.MaxDepth = 256;
|
||||
options.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles; // needed because file system API responses can have very nested structures
|
||||
options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
|
||||
});
|
||||
RouteDataStringKey = "culture",
|
||||
UIRouteDataStringKey = "culture",
|
||||
Options = requestLocalizationOptions
|
||||
};
|
||||
// make the route culture provider the first one to be evaluated
|
||||
requestLocalizationOptions.RequestCultureProviders =
|
||||
[
|
||||
routeDataRequestCultureProvider, // keep route-based culture handling
|
||||
new CookieRequestCultureProvider(), // but also add cookie option, so the application "remembers" the last used language the next time it's opened
|
||||
new AcceptLanguageHeaderRequestCultureProvider()
|
||||
];
|
||||
});
|
||||
|
||||
// configure cookie-based authentication
|
||||
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
|
||||
.AddCookie(options =>
|
||||
.AddCookie(cookieAuthenticationOptions =>
|
||||
{
|
||||
// basic path configuration
|
||||
options.LoginPath = "/auth/login";
|
||||
options.LogoutPath = "/auth/logout";
|
||||
options.AccessDeniedPath = "/auth/access-denied";
|
||||
cookieAuthenticationOptions.LoginPath = "/auth/login";
|
||||
cookieAuthenticationOptions.LogoutPath = "/auth/logout";
|
||||
cookieAuthenticationOptions.AccessDeniedPath = "/auth/access-denied";
|
||||
|
||||
// Cookie configuration
|
||||
options.Cookie = new CookieBuilder
|
||||
// cookie configuration
|
||||
cookieAuthenticationOptions.Cookie = new CookieBuilder
|
||||
{
|
||||
Name = ".Lumina.Auth", // unique name to avoid conflicts
|
||||
HttpOnly = true, // prevent JavaScript access
|
||||
SameSite = SameSiteMode.Lax, // balance between security and functionality
|
||||
SameSite = SameSiteMode.Strict,
|
||||
SecurePolicy = CookieSecurePolicy.Always, // require HTTPS
|
||||
Path = "/", // make cookie available for all paths
|
||||
IsEssential = true // mark as essential for GDPR
|
||||
};
|
||||
|
||||
// security settings
|
||||
options.ExpireTimeSpan = TimeSpan.FromHours(24); // TODO: perhaps make it configurable by user?
|
||||
options.SlidingExpiration = true;
|
||||
cookieAuthenticationOptions.ExpireTimeSpan = TimeSpan.FromHours(24); // TODO: perhaps make it configurable by user?
|
||||
cookieAuthenticationOptions.SlidingExpiration = true;
|
||||
|
||||
// handle validation to support various deployment scenarios
|
||||
options.Events = new CookieAuthenticationEvents
|
||||
cookieAuthenticationOptions.Events = new CookieAuthenticationEvents
|
||||
{
|
||||
// handle redirects to work with different base paths
|
||||
OnRedirectToLogin = context =>
|
||||
OnRedirectToLogin = redirectContext =>
|
||||
{
|
||||
// preserve any base path or subdirectory
|
||||
string redirectPath = context.RedirectUri;
|
||||
if (context.Request.PathBase.HasValue)
|
||||
redirectPath = context.Request.PathBase + options.LoginPath + new QueryString("?returnUrl=") + Uri.EscapeDataString(context.Request.PathBase + context.Request.Path);
|
||||
context.Response.Redirect(redirectPath);
|
||||
string culture = redirectContext.HttpContext.Request.RouteValues["culture"]?.ToString()?.ToLower() ?? "en-us";
|
||||
// preserve any base path or subdirectory and add return URL
|
||||
string redirectPath = redirectContext.RedirectUri;
|
||||
// insert culture into the path
|
||||
redirectPath = redirectPath.Replace("/auth/login", $"/{culture}/auth/login");
|
||||
if (redirectContext.Request.PathBase.HasValue)
|
||||
redirectPath = redirectContext.Request.PathBase + cookieAuthenticationOptions.LoginPath + new QueryString("?returnUrl=") + Uri.EscapeDataString(redirectContext.Request.PathBase + redirectContext.Request.Path);
|
||||
redirectContext.Response.Redirect(redirectPath);
|
||||
return Task.CompletedTask;
|
||||
},
|
||||
OnRedirectToLogout = redirectContext =>
|
||||
{
|
||||
string culture = redirectContext.HttpContext.Request.RouteValues["culture"]?.ToString()?.ToLower() ?? "en-us";
|
||||
string redirectPath = redirectContext.RedirectUri;
|
||||
redirectPath = redirectPath.Replace("/auth/logout", $"/{culture}/auth/logout");
|
||||
if (redirectContext.Request.PathBase.HasValue)
|
||||
redirectPath = redirectContext.Request.PathBase + cookieAuthenticationOptions.LogoutPath;
|
||||
redirectContext.Response.Redirect(redirectPath);
|
||||
return Task.CompletedTask;
|
||||
},
|
||||
OnRedirectToAccessDenied = redirectContext =>
|
||||
{
|
||||
string culture = redirectContext.HttpContext.Request.RouteValues["culture"]?.ToString()?.ToLower() ?? "en-us";
|
||||
string redirectPath = redirectContext.RedirectUri;
|
||||
redirectPath = redirectPath.Replace("/auth/access-denied", $"/{culture}/auth/access-denied");
|
||||
if (redirectContext.Request.PathBase.HasValue)
|
||||
redirectPath = redirectContext.Request.PathBase + cookieAuthenticationOptions.AccessDeniedPath;
|
||||
redirectContext.Response.Redirect(redirectPath);
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
};
|
||||
@@ -89,22 +163,22 @@ public static class PresentationWebLayerServices
|
||||
|
||||
// add an authorization policy that ensures application is initialized with super admin account before allowing access
|
||||
services.AddAuthorizationBuilder()
|
||||
.AddPolicy("RequireInitialization", policy => policy.Requirements.Add(new InitializationRequirement()));
|
||||
.AddPolicy("RequireInitialization", authorizationPolicyBuilder => authorizationPolicyBuilder.Requirements.Add(new InitializationRequirement()));
|
||||
|
||||
// add forwarded headers middleware to handle reverse proxy scenarios
|
||||
services.Configure<ForwardedHeadersOptions>(options =>
|
||||
services.Configure<ForwardedHeadersOptions>(forwardedHeadersOptions =>
|
||||
{
|
||||
options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto | ForwardedHeaders.XForwardedHost;
|
||||
options.KnownNetworks.Clear();
|
||||
options.KnownProxies.Clear();
|
||||
forwardedHeadersOptions.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto | ForwardedHeaders.XForwardedHost;
|
||||
forwardedHeadersOptions.KnownNetworks.Clear();
|
||||
forwardedHeadersOptions.KnownProxies.Clear();
|
||||
});
|
||||
|
||||
// configure session management to maintain user-specific data across requests
|
||||
services.AddSession(options =>
|
||||
services.AddSession(sessionOptions =>
|
||||
{
|
||||
options.IdleTimeout = TimeSpan.FromMinutes(30); // session expires after 30 minutes of inactivity
|
||||
options.Cookie.HttpOnly = true; // prevent JavaScript access to session cookie, for security
|
||||
options.Cookie.IsEssential = true; // mark session cookie as essential, for GDPR compliance
|
||||
sessionOptions.IdleTimeout = TimeSpan.FromMinutes(30); // session expires after 30 minutes of inactivity
|
||||
sessionOptions.Cookie.HttpOnly = true; // prevent JavaScript access to session cookie, for security
|
||||
sessionOptions.Cookie.IsEssential = true; // mark session cookie as essential, for GDPR compliance
|
||||
});
|
||||
|
||||
// scan the current assembly for validators and register them to the DI container
|
||||
@@ -113,16 +187,16 @@ public static class PresentationWebLayerServices
|
||||
// handle transient errors like network timeouts or intermittent failures
|
||||
AsyncRetryPolicy<HttpResponseMessage> retryPolicy = Policy<HttpResponseMessage>
|
||||
.Handle<HttpRequestException>()
|
||||
.OrInner<ApiException>(ex =>
|
||||
ex.HttpStatusCode != HttpStatusCode.BadRequest &&
|
||||
ex.HttpStatusCode != HttpStatusCode.Forbidden)
|
||||
.OrInner<ApiException>(apiException =>
|
||||
apiException.HttpStatusCode != HttpStatusCode.BadRequest && // do not retry Bad Request and Forbidden responses, it's pointless
|
||||
apiException.HttpStatusCode != HttpStatusCode.Forbidden)
|
||||
.WaitAndRetryAsync(3, retryAttempt =>
|
||||
TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)));
|
||||
|
||||
// use a circuit breaker to prevent repeatedly calling a failing service
|
||||
AsyncCircuitBreakerPolicy<HttpResponseMessage> circuitBreakerPolicy = Policy<HttpResponseMessage>
|
||||
.Handle<HttpRequestException>()
|
||||
.OrInner<ApiException>(ex => ex.HttpStatusCode == HttpStatusCode.InternalServerError)
|
||||
.OrInner<ApiException>(apiException => apiException.HttpStatusCode == HttpStatusCode.InternalServerError)
|
||||
.CircuitBreakerAsync(3, TimeSpan.FromSeconds(30));
|
||||
|
||||
AsyncPolicyWrap<HttpResponseMessage> policy = Policy.WrapAsync(retryPolicy, circuitBreakerPolicy);
|
||||
|
||||
@@ -6,8 +6,9 @@ using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Http.Extensions;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Mvc.Filters;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using Microsoft.Extensions.Localization;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
@@ -21,6 +22,20 @@ namespace Lumina.Presentation.Web.Common.Filters;
|
||||
/// </summary>
|
||||
public class ApiExceptionFilter : IExceptionFilter
|
||||
{
|
||||
private readonly IStringLocalizer<ApiExceptionFilter> _stringLocalizer;
|
||||
private readonly ILogger<ApiExceptionFilter> _logger;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ApiExceptionFilter"/> class with the specified localizer and logger.
|
||||
/// </summary>
|
||||
/// <param name="stringLocalizer">Injected service used for providing localized strings.</param>
|
||||
/// <param name="logger">Injected service used for logging.</param>
|
||||
public ApiExceptionFilter(IStringLocalizer<ApiExceptionFilter> stringLocalizer, ILogger<ApiExceptionFilter> logger)
|
||||
{
|
||||
_stringLocalizer = stringLocalizer;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Called after an action has thrown an Exception.
|
||||
/// </summary>
|
||||
@@ -30,11 +45,20 @@ public class ApiExceptionFilter : IExceptionFilter
|
||||
// check if the exception is an ApiException
|
||||
if (context.Exception is ApiException apiException)
|
||||
{
|
||||
// Log all available details for debugging/monitoring
|
||||
_logger.LogError(
|
||||
apiException,
|
||||
"API Exception occurred. Status: {StatusCode}, Title: {Title}, Detail: {Detail}, Extensions: {Extensions}",
|
||||
apiException.HttpStatusCode,
|
||||
apiException.ProblemDetails?.Title,
|
||||
apiException.ProblemDetails?.Detail,
|
||||
apiException.ProblemDetails?.Extensions);
|
||||
// handle unauthorized errors by prompting the user to re-login
|
||||
if (apiException.HttpStatusCode == HttpStatusCode.Unauthorized) // HTTP 401 Unauthorized actually means lack of valid authentication credentials (not logged in)
|
||||
{
|
||||
SignOutSynchronously(context.HttpContext);
|
||||
string currentUrl = context.HttpContext.Request.GetDisplayUrl();
|
||||
_logger.LogInformation("Redirecting unauthorized user to {Url}", currentUrl);
|
||||
context.HttpContext.Response.Redirect(currentUrl); // force an entire refresh of the current location, so that header and footer are re-rendered too
|
||||
}
|
||||
else
|
||||
@@ -42,33 +66,29 @@ public class ApiExceptionFilter : IExceptionFilter
|
||||
StringBuilder errorMessage = new();
|
||||
if (apiException.ProblemDetails is not null)
|
||||
{
|
||||
errorMessage.AppendLine($"HTTP {apiException.ProblemDetails.Status} {apiException.HttpStatusCode}<br>");
|
||||
// only show the meaningful error message to the user
|
||||
if (!string.IsNullOrEmpty(apiException.ProblemDetails.Detail))
|
||||
errorMessage.AppendLine($"<b>{apiException.ProblemDetails.Detail}<b>");
|
||||
errorMessage.AppendLine($"<b>{_stringLocalizer[apiException.ProblemDetails.Detail]}</b><br>");
|
||||
else if (!string.IsNullOrEmpty(apiException.ProblemDetails.Title))
|
||||
errorMessage.AppendLine($"<b>{apiException.ProblemDetails.Title}<b>");
|
||||
if (apiException.ProblemDetails.Extensions is not null && apiException.ProblemDetails.Extensions.TryGetValue("errors", out JsonElement errorsObj))
|
||||
errorMessage.AppendLine($"<b>{_stringLocalizer[apiException.ProblemDetails.Title]}</b><br>");
|
||||
|
||||
if (apiException.ProblemDetails.Extensions?.TryGetValue("errors", out JsonElement errorsObj) == true)
|
||||
{
|
||||
if (errorsObj is JsonElement jsonElement && jsonElement.ValueKind == JsonValueKind.Object)
|
||||
if (errorsObj.ValueKind == JsonValueKind.Object)
|
||||
{
|
||||
errorMessage.AppendLine("Validation Errors:");
|
||||
foreach (JsonProperty error in jsonElement.EnumerateObject())
|
||||
foreach (JsonProperty error in errorsObj.EnumerateObject())
|
||||
{
|
||||
string fieldName = error.Name;
|
||||
_logger.LogError("Validation error {Field}: {@ErrorValues}", error.Name, error.Value.EnumerateArray().Select(jsonElement => jsonElement.ToString()));
|
||||
if (error.Value.ValueKind == JsonValueKind.Array)
|
||||
foreach (JsonElement errorValue in error.Value.EnumerateArray())
|
||||
errorMessage.AppendLine($"- {fieldName}: {errorValue}<br>");
|
||||
errorMessage.AppendLine($"{_stringLocalizer[errorValue.ToString()]}<br>");
|
||||
}
|
||||
}
|
||||
}
|
||||
if (apiException.ProblemDetails.Extensions is not null)
|
||||
foreach (KeyValuePair<string, JsonElement> extension in apiException.ProblemDetails.Extensions)
|
||||
if (extension.Key != "errors")
|
||||
errorMessage.AppendLine($"{extension.Key}: {extension.Value}<br>");
|
||||
}
|
||||
else
|
||||
{
|
||||
errorMessage.AppendLine($"HTTP {apiException.HttpStatusCode}<br>");
|
||||
_logger.LogError(apiException, "Generic API error occurred");
|
||||
errorMessage.AppendLine($"{apiException.Message}<br>");
|
||||
}
|
||||
// return a JSON result with the error details
|
||||
@@ -81,6 +101,7 @@ public class ApiExceptionFilter : IExceptionFilter
|
||||
}
|
||||
else
|
||||
{
|
||||
_logger.LogError(context.Exception, "Unexpected exception occurred: {Message}", context.Exception.Message);
|
||||
// return a JSON result with the error details
|
||||
context.Result = new JsonResult(new
|
||||
{
|
||||
|
||||
@@ -20,7 +20,7 @@ public class InitializationCheckAttribute : ActionFilterAttribute
|
||||
public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
|
||||
{
|
||||
IAuthorizationService authorizationService = context.HttpContext.RequestServices.GetRequiredService<IAuthorizationService>();
|
||||
await authorizationService.AuthorizeAsync(context.HttpContext.User, context.HttpContext, "RequireInitialization");
|
||||
await next();
|
||||
await authorizationService.AuthorizeAsync(context.HttpContext.User, context.HttpContext, "RequireInitialization").ConfigureAwait(false);
|
||||
await next().ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.AspNetCore.Localization;
|
||||
using Microsoft.Extensions.Options;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Common.MiddlewareFilters;
|
||||
|
||||
/// <summary>
|
||||
/// Defines a pipeline for configuring middleware to handle localization.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// To use a MiddlewareFilter, you first need to create a pipeline. This acts as a mini startup configuration where you define an <see cref="IApplicationBuilder"/>
|
||||
/// to specify the middleware that should run as part of the pipeline. Multiple middleware can be configured in this way.
|
||||
/// </remarks>
|
||||
public class LocalizationPipeline
|
||||
{
|
||||
/// <summary>
|
||||
/// Configures the middleware pipeline to include the <see cref="RequestLocalizationMiddleware"/> for handling localization.
|
||||
/// </summary>
|
||||
/// <param name="app">The <see cref="IApplicationBuilder"/> used to configure the middleware pipeline.</param>
|
||||
/// <param name="options">The <see cref="IOptions{TOptions}"/> instance for <see cref="RequestLocalizationOptions"/>, containing localization settings to be applied.</param>
|
||||
public void Configure(IApplicationBuilder app, IOptions<RequestLocalizationOptions> options)
|
||||
{
|
||||
// runs the RequestLocalizationMiddleware with the provided options
|
||||
app.UseRequestLocalization(options.Value);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Localization;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Common.Middlewares;
|
||||
|
||||
/// <summary>
|
||||
/// Middleware to handle requests lacking a culture prefix in the URL, by redirecting to a default culture.
|
||||
/// </summary>
|
||||
public class CultureRedirectMiddleware
|
||||
{
|
||||
private readonly RequestDelegate _next;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="CultureRedirectMiddleware"/> class.
|
||||
/// </summary>
|
||||
/// <param name="next">The next middleware in the request pipeline.</param>
|
||||
public CultureRedirectMiddleware(RequestDelegate next)
|
||||
{
|
||||
_next = next;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles incoming requests and redirects to the default culture if necessary.
|
||||
/// </summary>
|
||||
/// <param name="context">The <see cref="HttpContext"/> for the current request.</param>
|
||||
public async Task InvokeAsync(HttpContext context)
|
||||
{
|
||||
// check if the request path starts with "/" and does not contain any culture
|
||||
string? path = context.Request.Path.Value?.ToLowerInvariant();
|
||||
// redirect routes that would lead to the home page
|
||||
if (path == "/" || path == "/home" || path == "/index")
|
||||
{
|
||||
// try to get the user's preferred culture from cookies
|
||||
IRequestCultureFeature? feature = context.Features.Get<IRequestCultureFeature>();
|
||||
string? userCulture = feature?.RequestCulture.Culture.Name;
|
||||
// if no specific culture is found, use "en-US" as fallback
|
||||
string redirectCulture = userCulture ?? "en-US";
|
||||
// redirect the user to their preferred culture route
|
||||
context.Response.Redirect($"/{redirectCulture.ToLower()}/");
|
||||
return;
|
||||
}
|
||||
await _next(context).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,8 @@
|
||||
namespace Lumina.Presentation.Web.Common.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Interface for the service for generating URLs from action and controller names, with URL localization.
|
||||
/// </summary>
|
||||
public interface IUrlService
|
||||
{
|
||||
/// <summary>
|
||||
|
||||
@@ -1,27 +1,34 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc.Controllers;
|
||||
using Microsoft.AspNetCore.Mvc.Infrastructure;
|
||||
using Microsoft.AspNetCore.Routing;
|
||||
using System;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Common.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Service for generating URLs from action and controller names.
|
||||
/// Service for generating URLs from action and controller names, with URL localization.
|
||||
/// </summary>
|
||||
public class UrlService : IUrlService
|
||||
{
|
||||
private readonly LinkGenerator _linkGenerator;
|
||||
private readonly IHttpContextAccessor _httpContextAccessor;
|
||||
private readonly IActionDescriptorCollectionProvider _actionDescriptorCollectionProvider;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UrlService"/> class.
|
||||
/// </summary>
|
||||
/// <param name="linkGenerator">The ASP.NET Core link generator service.</param>
|
||||
/// <param name="httpContextAccessor">Provides access to the current HTTP context.</param>
|
||||
public UrlService(LinkGenerator linkGenerator, IHttpContextAccessor httpContextAccessor)
|
||||
/// <param name="actionDescriptorCollectionProvider">The <see cref="IActionDescriptorCollectionProvider"/> used to retrieve information about the application's routes and actions.</param>
|
||||
public UrlService(LinkGenerator linkGenerator, IHttpContextAccessor httpContextAccessor, IActionDescriptorCollectionProvider actionDescriptorCollectionProvider)
|
||||
{
|
||||
_linkGenerator = linkGenerator;
|
||||
_httpContextAccessor = httpContextAccessor;
|
||||
_actionDescriptorCollectionProvider = actionDescriptorCollectionProvider;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -32,7 +39,25 @@ public class UrlService : IUrlService
|
||||
/// <returns>An absolute URL to the specified action.</returns>
|
||||
public string? GetAbsoluteUrl(string action, string controller)
|
||||
{
|
||||
string? scheme = _httpContextAccessor.HttpContext?.Request.Scheme;
|
||||
return _linkGenerator.GetUriByAction(_httpContextAccessor.HttpContext!, action: action, controller: controller, values: null, scheme: scheme);
|
||||
HttpContext? httpContext = _httpContextAccessor.HttpContext;
|
||||
if (httpContext is null)
|
||||
return null;
|
||||
string scheme = httpContext.Request.Scheme;
|
||||
string culture = httpContext.Request.RouteValues["culture"]?.ToString() ?? "en-US";
|
||||
// find the controller's route template
|
||||
ControllerActionDescriptor? controllerActionDescriptor = _actionDescriptorCollectionProvider
|
||||
.ActionDescriptors.Items
|
||||
.OfType<ControllerActionDescriptor>()
|
||||
.FirstOrDefault(ad =>
|
||||
ad.ControllerName.Equals(controller, StringComparison.OrdinalIgnoreCase) &&
|
||||
ad.ActionName.Equals(action, StringComparison.OrdinalIgnoreCase));
|
||||
if (controllerActionDescriptor is null)
|
||||
return null;
|
||||
// check if the route template contains {culture}
|
||||
string? routeTemplate = controllerActionDescriptor.AttributeRouteInfo?.Template;
|
||||
bool needsCulture = routeTemplate?.Contains("{culture}") == true;
|
||||
// create route values based on whether the controller is localized
|
||||
object values = needsCulture ? new { culture, action } : new { action };
|
||||
return _linkGenerator.GetUriByAction(httpContext: httpContext, action: action, controller: controller, values: values, scheme: scheme);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.Middlewares;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Common.Utilities;
|
||||
|
||||
/// <summary>
|
||||
/// Extension methods for making it easier for <see cref="CultureRedirectMiddleware"/> to be added the middleware.
|
||||
/// </summary>
|
||||
// Extension method to make it easier to add the middleware
|
||||
public static class CultureRedirectMiddlewareExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Adds the <see cref="CultureRedirectMiddleware"/> to the application's request pipeline.
|
||||
/// Redirects requests to include or validate the culture in the URL.
|
||||
/// </summary>
|
||||
/// <param name="builder">The <see cref="IApplicationBuilder"/> used to configure the application's request pipeline.</param>
|
||||
/// <returns>The <see cref="IApplicationBuilder"/> for further configuration.</returns>
|
||||
public static IApplicationBuilder UseCultureRedirect(this IApplicationBuilder builder)
|
||||
{
|
||||
return builder.UseMiddleware<CultureRedirectMiddleware>();
|
||||
}
|
||||
}
|
||||
@@ -52,7 +52,6 @@ public class FluentValidationOptions<TOptions> : IValidateOptions<TOptions> wher
|
||||
return ValidateOptionsResult.Success;
|
||||
|
||||
// if the validation fails, collect the error messages
|
||||
// TODO: add translation support for the error messages
|
||||
string[] errors = validationResult.Errors.Select(x => $"Options validation failed for '{x.PropertyName}' with error: '{x.ErrorMessage}'")
|
||||
.ToArray();
|
||||
|
||||
|
||||
Reference in new issue
Block a user