HttpContext.Current.Session is null in MVC 3 application

前端 未结 1 1800
隐瞒了意图╮
隐瞒了意图╮ 2020-12-09 00:45

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

相关标签:
1条回答
  • 2020-12-09 00:56

    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.

    0 讨论(0)
提交回复
热议问题