2020-04-01 20:00:27 +02:00
|
|
|
using Microsoft.AspNetCore.Http;
|
2021-02-18 11:06:02 +01:00
|
|
|
using Umbraco.Cms.Core.Web;
|
2020-04-01 20:00:27 +02:00
|
|
|
|
2022-05-09 09:39:46 +02:00
|
|
|
namespace Umbraco.Cms.Web.Common.AspNetCore;
|
2020-04-01 20:00:27 +02:00
|
|
|
|
2022-05-09 09:39:46 +02:00
|
|
|
public class AspNetCoreCookieManager : ICookieManager
|
|
|
|
|
{
|
|
|
|
|
private readonly IHttpContextAccessor _httpContextAccessor;
|
2020-04-01 20:00:27 +02:00
|
|
|
|
2022-05-09 09:39:46 +02:00
|
|
|
public AspNetCoreCookieManager(IHttpContextAccessor httpContextAccessor) =>
|
|
|
|
|
_httpContextAccessor = httpContextAccessor;
|
2020-04-01 20:00:27 +02:00
|
|
|
|
2022-05-09 09:39:46 +02:00
|
|
|
public void ExpireCookie(string cookieName)
|
|
|
|
|
{
|
|
|
|
|
HttpContext? httpContext = _httpContextAccessor.HttpContext;
|
2020-04-01 20:00:27 +02:00
|
|
|
|
2022-05-09 09:39:46 +02:00
|
|
|
if (httpContext is null)
|
2020-04-01 20:00:27 +02:00
|
|
|
{
|
2022-05-09 09:39:46 +02:00
|
|
|
return;
|
2020-04-01 20:00:27 +02:00
|
|
|
}
|
|
|
|
|
|
2022-05-09 09:39:46 +02:00
|
|
|
var cookieValue = httpContext.Request.Cookies[cookieName];
|
2020-06-03 17:17:30 +02:00
|
|
|
|
2022-05-09 09:39:46 +02:00
|
|
|
httpContext.Response.Cookies.Append(cookieName, cookieValue ?? string.Empty,
|
|
|
|
|
new CookieOptions { Expires = DateTime.Now.AddYears(-1) });
|
|
|
|
|
}
|
2020-04-01 20:00:27 +02:00
|
|
|
|
2022-05-09 09:39:46 +02:00
|
|
|
public string? GetCookieValue(string cookieName) => _httpContextAccessor.HttpContext?.Request.Cookies[cookieName];
|
2020-04-01 20:00:27 +02:00
|
|
|
|
2024-05-16 15:53:42 +02:00
|
|
|
public void SetCookieValue(string cookieName, string value, bool httpOnly) =>
|
|
|
|
|
_httpContextAccessor.HttpContext?.Response.Cookies.Append(cookieName, value, new CookieOptions { HttpOnly = httpOnly });
|
2022-05-09 09:39:46 +02:00
|
|
|
|
|
|
|
|
public bool HasCookie(string cookieName) => !(GetCookieValue(cookieName) is null);
|
2020-04-01 20:00:27 +02:00
|
|
|
}
|