Add GetCultureByAcceptLanguage extension for HttpContext

Introduced a new extension method, GetCultureByAcceptLanguage, in the WebExtensions class. This method parses the Accept-Language header from the HTTP request and returns the first valid CultureInfo, enabling detection of the user's preferred culture from browser settings.
This commit is contained in:
2026-02-11 13:54:27 +01:00
parent 670c8ed87c
commit 745e9c7bfe

View File

@@ -3,8 +3,10 @@ using EnvelopeGenerator.Application.Common.Dto.Receiver;
using EnvelopeGenerator.Web.Models;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.AspNetCore.Localization;
using Microsoft.AspNetCore.Mvc;
using System.Globalization;
using System.Security.Claims;
namespace EnvelopeGenerator.Web.Extensions;
@@ -116,4 +118,31 @@ public static class WebExtensions
Body = "Bitte kontaktieren Sie das IT-Team."
});
#endregion
#region HttpContext
public static CultureInfo? GetCultureByAcceptLanguage(this HttpContext context)
{
var acceptLanguage = context.Request.Headers.AcceptLanguage.ToString();
if (string.IsNullOrWhiteSpace(acceptLanguage))
return null;
foreach (var value in acceptLanguage.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
{
var cultureName = value.Split(';', 2)[0];
if (string.IsNullOrWhiteSpace(cultureName))
continue;
try
{
return new CultureInfo(cultureName);
}
catch (CultureNotFoundException)
{
// ignore invalid cultures and continue
}
}
return null;
}
#endregion
}