Application state (HttpApplicationStateBase)

 

有人是把 Application state 當全域變數來使用。

而 Application state 是什麼東東?直接看原文最清楚

Application state is a data repository available to all classes in an ASP.NET application. Application state is stored in memory on the server and is faster than storing and retrieving information in a database. Unlike session state, which is specific to a single user session, application state applies to all users and sessions. Therefore, application state is a useful place to store small amounts of often-used data that does not change from one user to another.

 

Advantages of application state: 

  1. Application variable data is multi-user global data stored in memory.
  2. Easy to access.
  3. Fast retrieval.
  4. Disadvantages of application state:

Disadvantages of application state:

  1. Application variable data is not able to survive the IIS restart and worker process recycling.
  2. Not suited for web farm and web garden like deployment situation.

 

範例:

using System.Web.Mvc;

namespace WebApplication1.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            HttpContext.Application["auth"] = "hello";
            
            return View();
        }

        public ActionResult About()
        {
            ViewBag.Message = HttpContext.Application["auth"];

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }
    }
}

 

參考資料:

HttpApplicationStateBase Class

ASP.NET Application State Overview

View State Vs. Session State Vs. Application State