|
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); |
|
} |
|
} |