Skip to content

Instantly share code, notes, and snippets.

@kuncevic
Created September 27, 2017 04:06
Show Gist options
  • Save kuncevic/b809e5f325b6e1b9add6f1d50cebb221 to your computer and use it in GitHub Desktop.
Save kuncevic/b809e5f325b6e1b9add6f1d50cebb221 to your computer and use it in GitHub Desktop.
aspnet core cooke manager, cookie helper
public class CookieManager
{
private readonly IHttpContextAccessor httpContextAccessor;
private readonly IDataProtector protecotr;
public CookieManager(IHttpContextAccessor httpContextAccessor, IDataProtectionProvider provider)
{
this.httpContextAccessor = httpContextAccessor;
this.protecotr = provider.CreateProtector(GetType().FullName);
}
/// <summary>
/// set the cookie
/// </summary>
/// <param name="key">key (unique indentifier)</param>
/// <param name="value">value to store in cookie object</param>
/// <param name="options">additional cookie options</param>
public void Set(string key, string value, CookieOptions options = null)
{
if (options == null)
{
options = new CookieOptions();
options.Expires = DateTime.Now.AddMinutes(25);
}
this.httpContextAccessor.HttpContext.Response.Cookies.Append(key, this.Encrypt(value), options);
}
/// <summary>
/// Get the cookie
/// </summary>
/// <param name="key">Key </param>
/// <returns>string value</returns>
public string Get(string key)
{
return this.Decrypt(this.httpContextAccessor.HttpContext.Request.Cookies[key]);
}
/// <summary>
/// Delete the key
/// </summary>
/// <param name="key">Key</param>
public void Remove(string key)
{
this.httpContextAccessor.HttpContext.Response.Cookies.Delete(key);
}
/// <summary>
/// Encrypting the cookie value (value should be a valid Base-64 string)
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
private string Encrypt(string value)
{
return protecotr.Protect(value);
}
/// <summary>
/// Decrypting the cookie value (value should be a valid Base-64 string)
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
private string Decrypt(string value)
{
return protecotr.Unprotect(value);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment