首页 > 代码库 > HttpContext.Cache属性

HttpContext.Cache属性

      HttpContext基于HttpApplication的处理管道,由于HttpContext对象贯穿整个处理过程,所以,可以从HttpApplication处理管道的前端将状态数据传递到管道的后端,完成状态的传递任务做个小demo

1.控制器:

  public class TestController : Controller    {        string key = "data";        public ActionResult Index()        {            return View();        }        /// <summary>        /// 定时器获取缓存数据        /// </summary>        /// <returns></returns>        [HttpPost]        public JsonResult GetData()        {            string data = http://www.mamicode.com/Convert.ToString(HttpContext.Cache.Get(this.key));           if (!string.IsNullOrEmpty(data))           {               return this.Json(new { success = true, data =http://www.mamicode.com/ data });           }           else           {               return this.Json(new { success = false, time = DateTime.Now.ToString("ss"), data =http://www.mamicode.com/ data });           }        }        /// <summary>        /// 打开输入缓存值界面        /// </summary>        /// <returns></returns>        [HttpGet]        public ActionResult CreateCacheData()        {            return View();        }        /// <summary>        /// 将数据插入缓存        /// </summary>        /// <param name="value"></param>        /// <returns></returns>        [HttpPost]        public void InsertCache(string value)        {            HttpContext.Cache.Insert(this.key, value);                 }    }

2.视图

Index.cshtml:

@{    ViewBag.Title = "Index";    Layout = null;}<script src="~/Scripts/jquery-1.8.2.min.js"></script><script src="~/Scripts/jquery.timers-1.2.js"></script><button id="btnStart">开始定时器</button><script>    $(function ()    {        //定时器开始        $("#btnStart").bind("click", function () {            $("body").everyTime("3s", "timer", function () {                $.ajax(                    {                        type: post,                        url: /Test/GetData,                        success: function (r) {                            if (r.success) {                                console.log("获取到数据,json字符串为" + JSON.stringify(r.data));                            }                            else {                                console.log("(" +r.time + ")秒没有获取到数据");                            }                        }                    });            })        });         })</script>
jquery.timers-1.2.js 是定时器jquery插件
定时器插件下载

CreateCacheData.cshtml:

@{    ViewBag.Title = "CreateCacheData";}<script src="~/Scripts/jquery-1.8.2.min.js"></script><input id="txtData"/><button id="btnSave" >    插入服务器缓存</button><script>    $(function () {        $("#btnSave").click(function ()        {            var getDataValue = $("#txtData").val();            $.post("/Test/InsertCache", {value:getDataValue}, function () {                alert("缓存插入成功");            });        })    });</script>

3.效果

技术分享

HttpContext.Cache属性