Skip to content

Instantly share code, notes, and snippets.

@poojarsn
Created October 14, 2021 09:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save poojarsn/047a4c193fdec41c0910f32450c33e38 to your computer and use it in GitHub Desktop.
Save poojarsn/047a4c193fdec41c0910f32450c33e38 to your computer and use it in GitHub Desktop.
Redis Cache Get Set PrivateSetterContractResolver
public class SessionService : ISessionService
{
private readonly ICryptoService _cryptoService;
private readonly string _encryptionKey = ConfigurationManager.AppSettings[AppSettingKeys.Common.SessionEncryptionKey];
public SessionService(ICryptoService cryptoService)
{
_cryptoService = cryptoService;
}
/// <summary>
/// Sets the object on to session
/// </summary>
/// <typeparam name="T"> Class type</typeparam>
/// <param name="key"> key </param>
/// <param name="value">object to be stored in session</param>
/// <param name="additionalKey">additional key</param>
public void Set<T>(SessionKeys key, T value, string additionalKey = null)
{
var sessionKey = ConstructSessionKey(key, additionalKey);
if (bool.Parse(ConfigurationManager.AppSettings[AppSettingKeys.Common.EncryptSessionData]))
{
var settings = new JsonSerializerSettings()
{
TypeNameHandling = TypeNameHandling.All,
ContractResolver = new PrivateSetterContractResolver()
};
HttpContext.Current.Session[sessionKey] = _cryptoService.EncryptWithCbc(JsonConvert.SerializeObject(value, settings), _encryptionKey);
HttpContext.Current.Items[sessionKey] = value;
}
else
{
HttpContext.Current.Session[sessionKey] = value;
}
}
/// <summary>
/// Gets from session; if not present, returns default(T).
/// </summary>
/// <typeparam name="T">Type</typeparam>
/// <param name="key"></param>
/// <param name="additionalKey"></param>
/// <returns>Object from session</returns>
public T Get<T>(SessionKeys key, string additionalKey = null)
{
var sessionKey = ConstructSessionKey(key, additionalKey);
if (HttpContext.Current.Session == null)
{
return default(T);
}
var o = HttpContext.Current.Session[sessionKey];
if (o == null) return default(T);
if (bool.Parse(ConfigurationManager.AppSettings[AppSettingKeys.Common.EncryptSessionData]))
{
if (HttpContext.Current.Items[sessionKey] != null)
return (T)HttpContext.Current.Items[sessionKey];
var settings = new JsonSerializerSettings()
{
TypeNameHandling = TypeNameHandling.All,
ContractResolver = new PrivateSetterContractResolver()
};
var returnObject = JsonConvert.DeserializeObject<T>(_cryptoService.DecryptWithCbc(o.ToString(), _encryptionKey), settings);
//http context cache (for this request)
HttpContext.Current.Items[sessionKey] = returnObject;
return returnObject;
}
else
{
return (T)o;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment