Search code examples
c#cookiessetcookie.net-7.0

Cookie is not working while redirecting in .NET 7


I need set cookie to redirect request but it's not working.. Everywhere everybody setting the cookie to Response property to Cookies but when I do it same so it's not working..

My Code:

        var token = "myToken123";
        var url = _configuration.GetValue<string>("Client:BaseUrl", string.Empty);

        Response.Cookies.Append("Token", token, new CookieOptions
        {
            Domain = url,
            IsEssential = true,
            Expires = DateTime.Now.AddDays(123),
            Secure = true,
            SameSite = SameSiteMode.None,
        });

        Response.Redirect(url!);

Solution

  • Possible reasons:

    • The Domain parameter of your cookie most probably poinst to another domain domain. You can't set cookies on other domains. This is forbidden for security reasons and won't work
    • The Secure parameter in your code forces the cookie to be only accepted over HTTPs, your site possibly works locally, over HTTP