我无法访问HttpContext.Application它总是返回null

时间:2013-10-03 06:25:31

标签: asp.net-mvc global httpcontext

这是我计算在线用户的代码 它在global.asax中运行良好,而且数量很好 但是当我从控制器调用它时它返回null

 void Session_Start(object sender, EventArgs e)
    {
        Application.Lock();
        Application["OnlineUsers"] = (int)Application["OnlineUsers"] + 1;
        Application.UnLock();
    }

    void Session_End(object sender, EventArgs e)
    {
        Application.Lock();
        Application["OnlineUsers"] = (int)Application["OnlineUsers"] - 1;
        Application.UnLock();
    }

    protected void Application_Start()
    {
        Application["OnlineUsers"] = 0;

    }
控制器中的

string strUsersOnline = HttpContext.Application["OnlineUsers"] as string;
        ViewData["OnlineUsers"] = strUsersOnline;

1 个答案:

答案 0 :(得分:0)

该值为null,因为as关键字使用显式转换或.ToString()

Refer MSDN