Search code examples
c#hangfire

Disable PreserveCultureAttribute in Hangfire


I am trying to use Hangfire to send a scheduled message to a user using the MS Bot Framework. However, all scheduled jobs fail with this:

System.Globalization.CultureNotFoundException

Culture is not supported. Parameter name: name en-HK is an invalid culture identifier.

System.Globalization.CultureNotFoundException: Culture is not supported.
Parameter name: name
en-HK is an invalid culture identifier.
   at System.Globalization.CultureInfo..ctor(String name, Boolean useUserOverride)
   at Hangfire.CaptureCultureAttribute.OnPerforming(PerformingContext filterContext)
   at Hangfire.Server.BackgroundJobPerformer.InvokePerformFilter(IServerFilter filter, PerformingContext preContext, Func`1 continuation)

Hangfire docs say that it's due to Culture Preserving and "It is done by the PreserveCultureAttribute class that is applied to all of your methods by default."

http://docs.hangfire.io/en/v1.1.0/features.html?highlight=preservecultureattribute

How can I disable the PreserveCultureAttribute in Hangfire so that it doesn't apply it to my methods?


Solution

  • How can I disable the PreserveCultureAttribute in Hangfire so that it doesn't apply it to my methods?

    I don't know exactly how to disable it but you can play with [PreserveCulture] attribute. Base on the exception you post I think the culture code is wrong. Check this link for correct culture code. Culture code for HK should be zh-HK.

    Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("zh-HK");
    BackgroundJob.Enqueue(() => NotifyNewComment(model.Id));
    
    [PreserveCulture]
    public static void NotifyNewComment(int commentId)
    {
        var currentCultureName = Thread.CurrentThread.CurrentCulture.Name;
        if (currentCultureName != "zh-HK")
        {
            throw new InvalidOperationException(String.Format("Current culture is {0}", currentCultureName));
        }
    }
    

    See reference https://github.com/HangfireIO/Hangfire/issues/77.

    I hope this will help you.