Harry89pl
Harry89pl

Reputation: 2435

SetCookie seems to not working correctly

What I'm trying to do is set cookie to Response after some Validation on backend.

Here is my code:

Controller

public class MyController : Controller
{
   public ActionResult Index()
   {
       var cookie = new HttpCookie("cookie-key", "true")
        {
            Expires = DateTime.Now.AddDays(30)
        };

        System.Web.HttpContext.Current.Response.SetCookie(cookie);
   }
}

But after that in System.Web.HttpContext.Current.Request.Cookies there is no cookie with key "cookie-key".

I've added a <sessionState cookieless="UseCookies" /> to my web.config file but it's doesn't help.

How can I make it work as it should? Am I missing something?

Edit:

I've changed SetCookie to Cookies.Add but it doesn't helped. Updated code:

public class MyController : Controller
{
   public ActionResult Index()
   {
       var cookie = new HttpCookie("cookie-key", "true")
       {
           Expires = DateTime.Now.AddDays(30)
       };

        System.Web.HttpContext.Current.Response.Cookies.Add(cookie);
   }
}

Upvotes: 2

Views: 9093

Answers (4)

Harry89pl
Harry89pl

Reputation: 2435

Found reason why this doesn't work. It was error with javascript framework reactjs. There was 500 internal server error but because of ajax call couldn't diagnose this.

Thanks guys for answers :)

Upvotes: 0

jtabuloc
jtabuloc

Reputation: 2535

Try this.

using System.Net;

var response = System.Web.HttpContext.Current.Response;

foreach( Cookie cook in response.Cookies)
{
     // set your expiration here
     cook.Expires = DateTime.MinValue;
}

Upvotes: 0

Andre Andersen
Andre Andersen

Reputation: 1211

SetCookie is for already existing Cookies.

You need to use Response.Cookies.Add(...)

That is all that is needed for your code to work.

Here is some code that I have in production that work 100%:

public ActionResult Login(string username, string password)
{
    var userService = new UserService();

    var loginResult = userService.ValidatePassword(username, password);

    if (loginResult == null) return Redirect("/");

    Response.Cookies.Add(new HttpCookie("tok", Uri.EscapeDataString(userService.CreateToken(loginResult)))
    {
        Expires = DateTime.Now.AddYears(1)
    });

    return Redirect("/admin");
}

Upvotes: 0

David Abaev
David Abaev

Reputation: 696

Try this code:

 HttpCookie cookie = new HttpCookie("cookie-key","true");
                cookie.Expires = DateTime.Now.AddDays(30);
                cookie.Path = "/";
                Response.Cookies.Add(cookie);
                Response.SetCookie(cookie);

1) Probably you need write location(path) 2) Sometimes good do Cookies.Add AND SetCookies

Upvotes: 1

Related Questions