How to set baseController object Id as key for outputcache

77 views Asked by At
 public class BaseController : Controller
    {
        // GET: Base
        public static UserManager.User _CurrentUser;
  }
}

This code is part of my BaseController and I want to use _CurrrentUser.Id as key for outputcache.

[OutputCache(Duration = 1200, VaryByCustom = _CurrentUser.Id)]

When I tried to do this, it say "Argument in attribute must be constant exprssion" and it's also need to set to static.

I can make this property static but how I can make it constant expression so I can use it for outputcache.

1

There are 1 answers

0
Mecit Semerci On BEST ANSWER

I recommend you should get CurrentUserId from Auth. Cookie. I use like that.

[Authorize]
public class BaseController : Controller
{
    private UserModel _currentUser;
    public UserModel CurrentUser => _currentUser ?? (_currentUser = GetCurrentUser());


    private UserModel GetCurrentUser()
    {
        UserModel currentUser;
        if (!User.Identity.IsAuthenticated) return null;
        try
        {
            var userDataFromCookie = CookieHelper.GetCookie(FormsAuthentication.FormsCookieName);

            if (string.IsNullOrWhiteSpace(userDataFromCookie))
                throw new ArgumentException("Authentication cookie is null");

            currentUser = JsonHelper.Deserialize<UserModel>(FormsAuthentication.Decrypt(userDataFromCookie)?.UserData);
        }
        catch (Exception)
        {

            throw;
        }


        return currentUser;
    }
}

Cookie Helper Method like that

  public static string GetCookie(string key)
    {
        return HttpContext.Current.Request.Cookies[key] != null ? HttpContext.Current.Request.Cookies[key].Value : null;
    }