Changed CultureMiddleware to check if the culture cookie value is in the list of supported languages, not just for null or empty. This ensures that only valid, supported culture values are accepted from the cookie; otherwise, the middleware falls back to Accept-Language or default logic.
39 lines
1.2 KiB
C#
39 lines
1.2 KiB
C#
using EnvelopeGenerator.Web.Extensions;
|
|
using EnvelopeGenerator.Web.Models;
|
|
using Microsoft.AspNetCore.Localization;
|
|
using Microsoft.Extensions.Options;
|
|
using System.Globalization;
|
|
|
|
namespace EnvelopeGenerator.Web.Middleware;
|
|
|
|
public class CultureMiddleware
|
|
{
|
|
private readonly RequestDelegate _next;
|
|
private readonly Cultures _cultures;
|
|
|
|
public CultureMiddleware(RequestDelegate next, IOptions<Cultures> culturesOpt)
|
|
{
|
|
_next = next;
|
|
_cultures = culturesOpt.Value;
|
|
}
|
|
|
|
public async Task InvokeAsync(HttpContext context)
|
|
{
|
|
var cookieName = CookieRequestCultureProvider.DefaultCookieName;
|
|
var cookieValue = context.Request.Cookies[cookieName];
|
|
|
|
if (!_cultures.Languages.Contains(cookieValue))
|
|
{
|
|
var requestCulture = context.GetCultureByAcceptLanguage()?.Name;
|
|
var culture = _cultures.GetOrDefault(requestCulture);
|
|
var cultureInfo = culture.Info ?? new CultureInfo(culture.Language);
|
|
|
|
context.Response.Cookies.SetCulture(culture.Language);
|
|
CultureInfo.CurrentCulture = cultureInfo;
|
|
CultureInfo.CurrentUICulture = cultureInfo;
|
|
}
|
|
|
|
await _next(context);
|
|
}
|
|
}
|