Hangfire background / recurring job culture issue


I use Hangfire to run background jobs in various .NET Core applications. Today I discovered that the wrong culture / UI culture is used — which results in incorrect formatting of dates (and much more). Not sure if this is a bug in Hangfire or ASP.NET Core. Found no explenation in the Hangfire documentation, and no quick fix on Stackoverflow.

If you encounter the same problem, it can be solved by creating a filter and adding it to GloabalJobFilters.

public class HangfireCultureFilter : JobFilterAttribute, IClientFilter { public string Culture { get; set; } public string UiCulture { get; set; } public HangfireCultureFilter() { Order = 0; } public void OnCreated(CreatedContext filterContext) {} public void OnCreating(CreatingContext filterContext) { filterContext.SetJobParameter("CurrentCulture", Culture); filterContext.SetJobParameter("CurrentUICulture", UiCulture); } }

And then add it to GlobalJobFilters in Starup.cs

public void Configure(IApplicationBuilder app) { var supportedCultures = new[] { new CultureInfo("sv-SE") }; app.UseRequestLocalization(new RequestLocalizationOptions { DefaultRequestCulture = new RequestCulture("sv-SE"), SupportedCultures = supportedCultures, SupportedUICultures = supportedCultures }); GlobalJobFilters.Filters.Add(new HangfireCultureFilter { Culture = "sv-SE", UiCulture = "sv-SE"}); app.UseHangfireDashboard(); ... }

That should do it.