Jay
Jay

Reputation: 5074

Cookie doesn't get saved in ASP.NET WebMethod

I'm trying to save a cookie in a WebMethod and retrieve it upon Page_Load. However the cookie doesn't get saved and it returns a null in the Page_Load event.

Here's my code:

WebMethod

[WebMethod]
public static string LoginUser(string email, string pass)
{
    //more code

    var ecookie= new HttpCookie("ecookie");
    ecookie["name"] = "roger";
    HttpContext.Current.Response.Cookies.Add(ecookie);
}

Page_Load

protected void Page_Load(object sender, EventArgs e)
{
    var response = HttpContext.Current.Response;
    if (response.Cookies["ecookie"]["name"] != null) //doesn't go inside this condition since it's null
    {
          string name = response.Cookies["ecookie"]["name"];
    }
}

What am I doing wrong?

Upvotes: 2

Views: 1274

Answers (1)

Nadir Muzaffar
Nadir Muzaffar

Reputation: 4842

You're saving the cookie value by the key userdata and are then retrieving it by the key ecookie.

Assuming you want to store the cookie with key ecookie, your WebMethod should probably look like:

[WebMethod]
public static string LoginUser(string email, string pass)
{
    //more code

    var ecookie= new HttpCookie("ecookie");
    ecookie["name"] = "roger";
    HttpContext.Current.Response.Cookies.Add(ecookie);
}

Upvotes: 1

Related Questions