1

This is how I'am saving cookie in my code which is a web service method. I tried to change the cookie expire time but still it is not working for me. Is there any issue with Context.Response to write cookie or Context.Request to read it??

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = false)]
public void SaveInDraft(FormRootObject _forms)
{
    HttpCookie formCookie = new HttpCookie("UserData");

    formCookie.Values.Add("formid", _forms.formid);

    foreach (var item in _forms.fielddata)
    {
        formCookie.Values.Add(item.id, item.value);
    }

    formCookie.Expires = DateTime.Now.AddYears(1);
    Context.Response.Cookies.Add(formCookie);

}

for retrieving this cookie on next page

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = false)]
public FormRootObject getDataFromCookie()
{
    FormRootObject form = new FormRootObject();
    List<formFielddata> lstFormFieldData = new List<formFielddata>();

    var getCookie=Context.Request.Cookies["UserData"];
    if (getCookie != null)
    {
        if (getCookie.Values.Count > 0)
        {
            foreach (var val in getCookie.Values)
            {
                formFielddata document = new formFielddata();

                if (val.ToString() != "formid")
                {
                    document.id = val.ToString();
                    document.value = getCookie[val.ToString()];
                    lstFormFieldData.Add(document);
                }
                else {
                    form.formid = getCookie[val.ToString()];
                }
            }

            form.fielddata = lstFormFieldData;
        }
    }

    return form;
}

but my object getCookie is always null

Raz Luvaton
  • 3,166
  • 4
  • 21
  • 36

2 Answers2

0

Rajesh, forms are only present on web applications. If you're using plain web api to create your service, no form is going to be presented to your service client.

To create a cookie: var resp = new HttpResponseMessage();

var cookie = new CookieHeaderValue("session-id", "12345");
cookie.Expires = DateTimeOffset.Now.AddDays(1);
cookie.Domain = Request.RequestUri.Host;
cookie.Path = "/";

resp.Headers.AddCookies(new CookieHeaderValue[] { cookie });
return resp;

To consume cookie:

CookieHeaderValue cookie = Request.Headers.GetCookies("session-id")
Bruno Moreira
  • 175
  • 3
  • 15
0

I got this by storing cookies as

HttpContext.Current.Response.Cookies.Add(formCookie);

And reading this as

var getCookie=HttpContext.Current.Request.Cookies["UserData"];
  • though this worked for me but as my requirements user should be able to store cookie and retrieve those back without internet connectivity it is better to save cookie using javascript .[link](https://stackoverflow.com/questions/14573223/set-cookie-and-get-cookie-with-javascript) – Rajesh Parab Jul 12 '17 at 12:11