80 lines
3.0 KiB
C#
80 lines
3.0 KiB
C#
|
using System;
|
|||
|
using Microsoft.AspNetCore.CookiePolicy;
|
|||
|
using Microsoft.AspNetCore.Http;
|
|||
|
|
|||
|
namespace FAuth.Extensions
|
|||
|
{
|
|||
|
/// <summary>
|
|||
|
/// cookie帮助类
|
|||
|
/// </summary>
|
|||
|
public static class CookieHelper
|
|||
|
{
|
|||
|
/// <summary>
|
|||
|
/// 设置Cookie值
|
|||
|
/// </summary>
|
|||
|
/// <param name="httpContext">http上下文</param>
|
|||
|
/// <param name="key">Cookie的键</param>
|
|||
|
/// <param name="value">cookie值</param>
|
|||
|
/// <param name="minutes">cookie有效期。分钟,无限传null或不传</param>
|
|||
|
public static void SetCookies(this HttpContext httpContext,string key,string value,int? minutes = null) {
|
|||
|
SetCookies(httpContext.Response,key,value,minutes);
|
|||
|
}
|
|||
|
|
|||
|
/// <summary>
|
|||
|
/// 设置Cookie值
|
|||
|
/// </summary>
|
|||
|
/// <param name="response">http响应</param>
|
|||
|
/// <param name="key">Cookie的键</param>
|
|||
|
/// <param name="value">cookie值</param>
|
|||
|
/// <param name="minutes">cookie有效期。分钟,无限传null或不传</param>
|
|||
|
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);
|
|||
|
}
|
|||
|
}
|
|||
|
/// <summary>
|
|||
|
/// 删除cookie
|
|||
|
/// </summary>
|
|||
|
/// <param name="httpContext">http上下文</param>
|
|||
|
/// <param name="key">要删除的键</param>
|
|||
|
public static void DeleteCookies(this HttpContext httpContext,string key) {
|
|||
|
DeleteCookies(httpContext.Response,key);
|
|||
|
}
|
|||
|
|
|||
|
/// <summary>
|
|||
|
/// 删除cookie
|
|||
|
/// </summary>
|
|||
|
/// <param name="response">http响应</param>
|
|||
|
/// <param name="key">要删除的键</param>
|
|||
|
public static void DeleteCookies(this HttpResponse response,string key) {
|
|||
|
response.Cookies.Delete(key);
|
|||
|
}
|
|||
|
/// <summary>
|
|||
|
/// 获取cookie中的值
|
|||
|
/// </summary>
|
|||
|
/// <param name="httpContext">http上下文</param>
|
|||
|
/// <param name="key">cookie的键</param>
|
|||
|
/// <returns>保存的值</returns>
|
|||
|
public static string GetCookiesValue(this HttpContext httpContext,string key) {
|
|||
|
return GetCookiesValue(httpContext.Request,key);
|
|||
|
}
|
|||
|
|
|||
|
/// <summary>
|
|||
|
/// 获取cookie中的值
|
|||
|
/// </summary>
|
|||
|
/// <param name="request">http请求</param>
|
|||
|
/// <param name="key">cookie的键</param>
|
|||
|
/// <returns>保存的值</returns>
|
|||
|
public static string GetCookiesValue(this HttpRequest request,string key) {
|
|||
|
if(request.Cookies.TryGetValue(key,out string value)) {
|
|||
|
return value;
|
|||
|
}
|
|||
|
return string.Empty;
|
|||
|
}
|
|||
|
}
|
|||
|
}
|