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:
@@ -3,8 +3,10 @@ using EnvelopeGenerator.Application.Common.Dto.Receiver;
|
|||||||
using EnvelopeGenerator.Web.Models;
|
using EnvelopeGenerator.Web.Models;
|
||||||
using Microsoft.AspNetCore.Authentication;
|
using Microsoft.AspNetCore.Authentication;
|
||||||
using Microsoft.AspNetCore.Authentication.Cookies;
|
using Microsoft.AspNetCore.Authentication.Cookies;
|
||||||
|
using Microsoft.AspNetCore.Http.HttpResults;
|
||||||
using Microsoft.AspNetCore.Localization;
|
using Microsoft.AspNetCore.Localization;
|
||||||
using Microsoft.AspNetCore.Mvc;
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
using System.Globalization;
|
||||||
using System.Security.Claims;
|
using System.Security.Claims;
|
||||||
|
|
||||||
namespace EnvelopeGenerator.Web.Extensions;
|
namespace EnvelopeGenerator.Web.Extensions;
|
||||||
@@ -116,4 +118,31 @@ public static class WebExtensions
|
|||||||
Body = "Bitte kontaktieren Sie das IT-Team."
|
Body = "Bitte kontaktieren Sie das IT-Team."
|
||||||
});
|
});
|
||||||
#endregion
|
#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
|
||||||
}
|
}
|
||||||
Reference in New Issue
Block a user