简体   繁体   中英

How to write and check cookie in Dot Net Core

I'm trying to create a basic cookie and check that it's available in my code but it doesn't work and I suspect I am missing something obvious.

private JwtSecurityToken GetJsonWebTokenFromCookie()
{
    var personId = 0;
    var jwt = new JwtSecurityToken();

#if DEBUG

    Response.Cookies.Append(".FAPPSOUSR", "pid=48527257", new CookieOptions
    {
        Domain = "localhost",
        Expires = DateTime.Now.AddDays(1),
        Path = "/",
    });

#endif

    var cookieValueFromContext = HttpContext.Request.Cookies[".FAPPSOUSR"];

    if (string.IsNullOrEmpty(cookieValueFromContext)) return null;

    if (Request.Cookies["pid"] != null)
    {
        var value = Request.Cookies["pid"];
        int.TryParse(value, out personId);
        if (personId == 0) return null;
    }

    jwt.Claims.Append(new Claim("nameid", personId.ToString()));
    return jwt;
}

This is always null:

var cookieValueFromContext = HttpContext.Request.Cookies[".FAPPSOUSR"];

I have written wrapper on top of http cookie which helps to ease of use. it has silent features.

  • Strongly Typed
  • Securing Cookie Data to protect
  • Easy options to configure CookieManager
  • Ease to use

try out here

add the CookieManager in configure service in start up class

//add CookieManager
services.AddCookieManager();

getting the Cookie object

MyCookie objFromCookie = _cookieManager.Get<MyCookie>("Key");

set the Cookie object

_cookieManager.Set("Key", cooObj, 60);

hope it helps you

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM