How can I cache objects in ASP.NET MVC?

后端 未结 8 1044
一生所求
一生所求 2020-12-04 06:25

I\'d like to cache objects in ASP.NET MVC. I have a BaseController that I want all Controllers to inherit from. In the BaseController there is a User

8条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-04 06:38

    If you want it cached for the length of the request, put this in your controller base class:

    public User User {
        get {
            User _user = ControllerContext.HttpContext.Items["user"] as User;
    
            if (_user == null) {
                _user = _repository.Get(id);
                ControllerContext.HttpContext.Items["user"] = _user;
            }
    
            return _user;
        }
    }
    

    If you want to cache for longer, use the replace the ControllerContext call with one to Cache[]. If you do choose to use the Cache object to cache longer, you'll need to use a unique cache key as it will be shared across requests/users.

提交回复
热议问题