35 lines
1.1 KiB
C#
35 lines
1.1 KiB
C#
namespace Yuna.Website.Server.Infrastructure
|
|
{
|
|
public static class CookieExtensions
|
|
{
|
|
public static T LoadFromCookies<T>(this HttpContext context, string key)
|
|
{
|
|
if (context.Request.Cookies.TryGetValue(key, out var value))
|
|
{
|
|
try
|
|
{
|
|
return System.Text.Json.JsonSerializer.Deserialize<T>(value)
|
|
?? throw new Exception();
|
|
}
|
|
|
|
catch
|
|
{
|
|
return default!;
|
|
}
|
|
}
|
|
|
|
return default!;
|
|
}
|
|
|
|
public static void SaveToCookies<T>(this HttpContext context, string key, T value, TimeSpan? maxAge = null)
|
|
{
|
|
var dataStr = System.Text.Json.JsonSerializer.Serialize<T>(value);
|
|
|
|
if (context.Request.Cookies.ContainsKey(key)) context.Response.Cookies.Delete(key);
|
|
|
|
context.Response.Cookies.Append(key, dataStr, new CookieOptions() { HttpOnly = true, MaxAge = maxAge ?? TimeSpan.FromDays(365) });
|
|
}
|
|
|
|
}
|
|
}
|