that is amazing @skttl thank you - dunno why i didn’t think of using the umbraco helper (tbh i don’t use it a lot…) but it works a treat ![]()
just in case anyone else stumbles across this…
the helper works great in a controller but becomes tricker in an api controller…
the way we’ve solved it is to create a filter:
using Microsoft.AspNetCore.Mvc.Filters;
using System.Globalization;
namespace YourSite.Core.Filters
{
public class SetCultureFromHeaderFilter : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext context)
{
var cultureHeader = context.HttpContext.Request.Headers["Accept-Language"].FirstOrDefault();
if (!string.IsNullOrWhiteSpace(cultureHeader))
{
try
{
var culture = new CultureInfo(cultureHeader);
Thread.CurrentThread.CurrentCulture = culture;
Thread.CurrentThread.CurrentUICulture = culture;
}
catch (CultureNotFoundException)
{
//we could set a default culture here if we wanted
}
}
base.OnActionExecuting(context);
}
}
}
then that gets applied to all the api controllers:
namespace YourSite.Core.Controllers.Api
{
[ApiController]
[SetCultureFromHeaderFilter]
public class YourApiController : Controller
{
...
we set the language on the html tag:
<!doctype html>
<html lang="es">
<head>
...
and pass the header in the javascript that calls any of the endpoints:
const currentCulture = document.documentElement.lang;
const response = await fetch('/api/your-end-point', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept-Language': currentCulture,
}
...
});
the api controller and any of the code it consumes now knows the correct culture. nice.