using System;
using Microsoft.AspNetCore.CookiePolicy;
using Microsoft.AspNetCore.Http;
namespace FAuth.Extensions
{
///
/// cookie帮助类
///
public static class CookieHelper
{
///
/// 设置Cookie值
///
/// http上下文
/// Cookie的键
/// cookie值
/// cookie有效期。分钟,无限传null或不传
public static void SetCookies(this HttpContext httpContext,string key,string value,int? minutes = null) {
SetCookies(httpContext.Response,key,value,minutes);
}
///
/// 设置Cookie值
///
/// http响应
/// Cookie的键
/// cookie值
/// cookie有效期。分钟,无限传null或不传
public static void SetCookies(this HttpResponse response,string key,string value,int? minutes = null) {
if(minutes.HasValue) {
response.Cookies.Append(key,value,new CookieOptions {
Expires = DateTime.Now.AddMinutes(minutes.Value)
});
} else {
response.Cookies.Append(key,value);
}
}
///
/// 删除cookie
///
/// http上下文
/// 要删除的键
public static void DeleteCookies(this HttpContext httpContext,string key) {
DeleteCookies(httpContext.Response,key);
}
///
/// 删除cookie
///
/// http响应
/// 要删除的键
public static void DeleteCookies(this HttpResponse response,string key) {
response.Cookies.Delete(key);
}
///
/// 获取cookie中的值
///
/// http上下文
/// cookie的键
/// 保存的值
public static string GetCookiesValue(this HttpContext httpContext,string key) {
return GetCookiesValue(httpContext.Request,key);
}
///
/// 获取cookie中的值
///
/// http请求
/// cookie的键
/// 保存的值
public static string GetCookiesValue(this HttpRequest request,string key) {
if(request.Cookies.TryGetValue(key,out string value)) {
return value;
}
return string.Empty;
}
}
}