FalconSSO/FAuth/Extensions/CookieHelper.cs

80 lines
3.0 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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