Improve culture cookie handling and localization responses
Refactored GetCulture to return null if cookie is missing or invalid, and added GetCultureOrDefault for fallback. Updated TestLocalizerController and CultureMiddleware to use new methods for more accurate culture detection. Localizer now returns only the localized string value.
This commit is contained in:
@@ -24,7 +24,7 @@ namespace EnvelopeGenerator.Web.Controllers.Test
|
||||
}
|
||||
|
||||
[HttpGet("{key}")]
|
||||
public IActionResult Localize([FromRoute] string key) => Ok(_localizer[key]);
|
||||
public IActionResult Localize([FromRoute] string key) => Ok(_localizer[key].Value);
|
||||
|
||||
[HttpGet("fi-class")]
|
||||
public IActionResult GetFIClass(string? lang = null) => lang is null ? Ok(_cultures.FIClasses) : Ok(_cultures[lang]?.FIClass);
|
||||
@@ -39,6 +39,6 @@ namespace EnvelopeGenerator.Web.Controllers.Test
|
||||
: NotFound();
|
||||
|
||||
[HttpGet("culture/user")]
|
||||
public IActionResult GetUserCulture() => Request.Cookies.GetCulture() is string cult ? Ok(cult) : NotFound();
|
||||
public IActionResult GetUserCulture() => Request.Cookies.GetCultureOrDefault() is string cult ? Ok(cult) : NotFound();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -60,20 +60,16 @@ public static class WebExtensions
|
||||
#endregion
|
||||
|
||||
#region Cookie
|
||||
public static string GetCulture(this IRequestCookieCollection cookies)
|
||||
public static string? GetCulture(this IRequestCookieCollection cookies)
|
||||
{
|
||||
var cookieValue = cookies[CookieRequestCultureProvider.DefaultCookieName];
|
||||
|
||||
if (!string.IsNullOrEmpty(cookieValue))
|
||||
{
|
||||
var culture = CookieRequestCultureProvider.ParseCookieValue(cookieValue)?.Cultures.FirstOrDefault().Value;
|
||||
if (!string.IsNullOrEmpty(culture))
|
||||
return culture;
|
||||
}
|
||||
|
||||
return CultureInfo.CurrentUICulture.Name;
|
||||
if (cookies[CookieRequestCultureProvider.DefaultCookieName] is string cookieValue)
|
||||
return CookieRequestCultureProvider.ParseCookieValue(cookieValue)?.Cultures.FirstOrDefault().Value;
|
||||
else
|
||||
return null;
|
||||
}
|
||||
|
||||
public static string GetCultureOrDefault(this IRequestCookieCollection cookies) => GetCulture(cookies) ?? CultureInfo.CurrentCulture.Name;
|
||||
|
||||
public static void SetCulture(this IResponseCookies cookies, string culture)
|
||||
{
|
||||
var cookieOptions = new CookieOptions
|
||||
|
||||
@@ -19,8 +19,7 @@ public class CultureMiddleware
|
||||
|
||||
public async Task InvokeAsync(HttpContext context)
|
||||
{
|
||||
var cookieName = CookieRequestCultureProvider.DefaultCookieName;
|
||||
var cookieValue = context.Request.Cookies[cookieName];
|
||||
var cookieValue = context.Request.Cookies.GetCulture();
|
||||
|
||||
if (!_cultures.Languages.Contains(cookieValue))
|
||||
{
|
||||
|
||||
Reference in New Issue
Block a user