mardi 26 janvier 2016

Cooki Valua and ExpireDate are wrong - MVC

I have a ASP.NET MVC 5 project. I have two languages in my project, to set language I use the code below:

BaseController

  protected override void ExecuteCore()
    {
        HttpCookie cookie;
        if (RouteData.Values["lang"] != null && !string.IsNullOrWhiteSpace(RouteData.Values["lang"].ToString()))
        {
            var lang = RouteData.Values["lang"].ToString();
            Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(lang);
        }
        else
        {
            cookie = HttpContext.Request.Cookies["imen.lang"];
            string langHeader;
            if (cookie != null)
            {
                langHeader = cookie.Value;
                Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(langHeader);
            }
            else
            {
                langHeader = "fa-IR";
                Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(langHeader);
            }

            RouteData.Values["lang"] = langHeader;
        }

        cookie = new HttpCookie("imen.lang", Thread.CurrentThread.CurrentUICulture.Name) { Expires = DateTime.Now.AddYears(1) };
        if (HttpContext.Response.RedirectLocation == null)
            HttpContext.Response.SetCookie(cookie);
        base.ExecuteCore();
    }

It works fine, but I cache a methods by lang and User below code in Global.asax like this :

    public override string GetVaryByCustomString(HttpContext context, string custom)
    {
        if ("lang".Equals(custom))
        {
            var cookie = HttpContext.Current.Request.Cookies["imen.lang"];
            var culture = cookie != null
                              ? CultureInfo.CreateSpecificCulture(cookie.Value).Name
                              : Guid.NewGuid().ToString();  
            return culture;

        }
        return base.GetVaryByCustomString(context, custom);
    }

Problems :

1- when Read Cooki in GetVaryByCustomString in Global ExpireDate is 01/01/0001 12:00:00 AM

2- when change Language , firstTime Cooki value is not same to current Language and it equals to Previour Language.

whats Problem ?

Aucun commentaire:

Enregistrer un commentaire