ASP.NET MVC. Multilingual site. Set invariant culture for all DateTime's despite user's culture

757 views Asked by At

I develop multilingual site. Users can change preferred language, so i set current culture for each request like so:

System.Threading.Thread.CurrentThread.CurrentCulture = /* user preferred culture */
System.Threading.Thread.CurrentThread.CurrentUICulture = /* user preferred culture */

My domain entities have property DateAdded (to set the date the record was created):

public class EntityBase
{
    protected EntityBase()
    {
        DateAdded = DateTime.UtcNow;
    }

    [Required]
    public int Id { get; set; }

    public DateTime DateAdded { get; set; }

}

My question is: how can i interact globally with all DateTime's in my WebApplication with Invariant Culture despite user's culture? I want to save DateTime's in database (im using Entity Framework), update them, calculate them, parse strings in invariant culture etc. I'll show DateTime in user's culture where it's needed only.

1

There are 1 answers

0
Sam Alekseev On

Well, my biggest problem was i set CurrentCulture too late. I set it in controller's OnActionExecuting method like so:

public abstract class BaseController : Controller
{
    protected override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var culture = GetUserCultureSomehow();
        var cultureInfo = new System.Globalization.CultureInfo(culture);
        System.Threading.Thread.CurrentThread.CurrentUICulture = cultureInfo;
        System.Threading.Thread.CurrentThread.CurrentCulture = cultureInfo;
        base.OnActionExecuting(filterContext);
    }
}

But it is too late in some scenarios, i.e. ModelBinder binds data from POST request before any action is called.

I moved this logic up the request pipeline, i.e.:

protected void Application_PostAcquireRequestState(object sender, EventArgs e)
    {
        //set culture here;
    }

This ensures culture is set as soon as possible for every request. After this i have no problems with converting strings to DateTime.