using Microsoft.AspNetCore.Http;
using System;
using System.Net;
namespace Znyc.Recruitment.Admin.Commons.Helpers
{
///
/// Cookie操作类
///
public static class CookiesHelper
{
///
///
public static HttpContext HttpHelper => HttpContextHelper.HttpContext;
///
/// Cookie名称
///
public static string CookieName { get; set; } = "Znyc_";
///
/// 设置Cookie键
///
/// 键
///
private static string CookieKey(string cookieName)
{
return CookieName + cookieName;
}
///
/// 删除Cookie
///
///
/// Coookie名称
public static void DeleteCookie(HttpContext context, string cookieName)
{
string key = CookieKey(cookieName);
context.Response.Cookies.Delete(key);
}
///
/// 写/保存Cookie
///
///
/// Coookie名称
/// Coookie值
/// 有效月数
public static void WriteCookie(HttpContext context, string cookieName, string value, int months)
{
WriteCookie(context, cookieName, value, months, 0);
}
///
/// 写/保存Cookie
///
/// Coookie名称
/// Coookie值
/// 有效月数
public static void WriteCookie(string cookieName, string value, int months)
{
WriteCookie(HttpHelper, cookieName, value, months, 0);
}
///
/// 写/保存Cookie
///
///
/// Coookie名称
/// Coookie值
/// 有效月数
/// 有效天数
public static void WriteCookie(HttpContext context, string cookieName, string value, int months, int days)
{
string key = CookieKey(cookieName);
if (!context.Request.Cookies.ContainsKey(key))
{
DateTime expires = DateTime.Today.AddDays(30 * months + days);
DateTimeOffset dateAndOffset = new DateTimeOffset(expires,
TimeZoneInfo.Local.GetUtcOffset(expires));
context.Response.Cookies.Append(key, value,
new CookieOptions
{
Expires = expires
});
}
}
///
/// 获取Cookie值
///
///
/// Coookie名称
///
public static string ReadCookie(HttpContext context, string cookieName)
{
string key = CookieKey(cookieName);
try
{
return WebUtility.UrlDecode(context.Request.Cookies[key]);
}
catch
{
return "";
}
}
///
/// 获取Cookie值
///
/// Coookie名称
///
public static string ReadCookie(string cookieName)
{
string key = CookieKey(cookieName);
try
{
return WebUtility.UrlDecode(HttpHelper.Request.Cookies[key]);
}
catch
{
return "";
}
}
}
}