首先创建Basic类型mvc项目.
然后:
HomeController.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace GlobalApplicationObjectTest.Controllers
{
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index()
{
return View();
}
public ActionResult SessionAbandon()
{
Session.Abandon();
return View("Index");
}
}
}
Index.cshtml:
@using System.Web;
@{
ViewBag.Title = "Index";
}
<h2>在线人数:@HttpContext.Current.Application["OnLineUserCount"]</h2>
<hr />
<h2>@Html.ActionLink("离开","SessionAbandon")</h2>
Global.asax.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
namespace GlobalApplicationObjectTest
{
// 注意: 有关启用 IIS6 或 IIS7 经典模式的说明,
// 请访问 http://go.microsoft.com/?LinkId=9394801
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
Application["OnLineUserCount"] = 0;
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
protected void Session_Start(object sender, EventArgs e)
{
Application.Lock();
Application["OnLineUserCount"] = Convert.ToInt32(Application["OnLineUserCount"]) + 1;
Application.UnLock();
}
protected void Session_End(object sender, EventArgs e)
{
Application.Lock();
Application["OnLineUserCount"] = Convert.ToInt32(Application["OnLineUserCount"]) - 1;
Application.UnLock();
}
}
}