mardi 30 juin 2015

Setting the Culture per request is impossible in ASP.NET

Setting the culture settings per request should be easy, right? Well it isn't because you set the culture settings on a thread not a request and apparently ASP.NET doesn't always execute the whole request on a single thread. Sure I could use DefaultThreadCurrentCulture, but that would set the culture on all threads, not just the ones used by the specific request.

So am I missing something here or what? Because when I set the culture in Global.asax's Application_AcquireRequestState() function (so it executes once at the beginning of each request) for some reason I have property display names popping up in multiple languages and when I dug deeper, I found out that in the Display Name Attribute's constructor the CurrentCulture and CurrentUICulture settings are sometimes completely different from what I set in Global.asax.

I'm sure that the problem isn't in my customized display name attribute, but you can see it below anyway:

public class DDisplayName : DisplayNameAttribute
        public DDisplayName(string resourceId)
            : base(GetAttributeName(resourceId))
        {  }

        private static string GetAttributeName(string resourceId)
            var lang = System.Threading.Thread.CurrentThread.CurrentCulture.LCID + "|" + System.Threading.Thread.CurrentThread.CurrentUICulture.LCID;

            ResourceManager resMan = new ResourceManager(typeof(Strings));

            string result = resMan.GetString(resourceId);

            return result == null ? "Resource string: " + resourceId + " not found" : result+" "+lang;


As you can see I even added the LCIDs do the display name so I can see them on the screen, and the Culture Settings are different.

Aucun commentaire:

Enregistrer un commentaire