Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
773 views
in Technique[技术] by (71.8m points)

asp.net mvc 3 - HttpContext.Current.Session is null in MVC 3 application

I have a bilingual MVC 3 application, I use cookies and session to save "Culture" in Session_start method inside Global.aspx.cs file, but direct after it, the session is null.

This is my code:

    protected void Session_Start(object sender, EventArgs e)
    {
        HttpCookie aCookie = Request.Cookies["MyData"];

        if (aCookie == null)
        {
            Session["MyCulture"] = "de-DE";
            aCookie = new HttpCookie("MyData");
            //aCookie.Value = Convert.ToString(Session["MyCulture"]);
            aCookie["MyLang"] = "de-DE";
            aCookie.Expires = System.DateTime.Now.AddDays(21);
            Response.Cookies.Add(aCookie);
        }
        else
        {
            string s = aCookie["MyLang"];
            HttpContext.Current.Session["MyCulture"] = aCookie["MyLang"];
        }
 }

and second time it goes into the "else clause" because the cookie exists; inside my Filter, when it tries set the culutre, Session["MyCulture"] is null.

   public void OnActionExecuting(ActionExecutingContext filterContext)
    {

        System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(HttpContext.Current.Session["MyCulture"].ToString());
        System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.CreateSpecificCulture(HttpContext.Current.Session["MyCulture"].ToString());
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Why are you using HttpContext.Current in an ASP.NET MVC application? Never use it. That's evil even in classic ASP.NET webforms applications but in ASP.NET MVC it's a disaster that takes all the fun out of this nice web framework.

Also make sure you test whether the value is present in the session before attempting to use it, as I suspect that in your case it's not HttpContext.Current.Session that is null, but HttpContext.Current.Session["MyCulture"]. So:

public void OnActionExecuting(ActionExecutingContext filterContext)
{
    var myCulture = filterContext.HttpContext.Session["MyCulture"] as string;
    if (!string.IsNullOrEmpty(myCulture))
    {
        Thread.CurrentThread.CurrentUICulture = new CultureInfo(myCulture);
        Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(myCulture);
    }
}

So maybe the root of your problem is that Session["MyCulture"] is not properly initialized in the Session_Start method.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...