I'm new to C# and .net and have written a code in order to create a cookie using this code:
HttpCookie userInfo = new HttpCookie("userInfo");
userInfo["userName"] = "user1";
userInfo["logdata"] = "data1";
userInfo.Expires.Add(new TimeSpan(0, 1, 0));
I want to add this cookie to the browser cookies with specific URI, so that the back-end code can see my new added cookie and read the data in theat cookie. I have used this code:
myURI = new Uri(strURI);
request = (HttpWebRequest)HttpWebRequest.Create(myURI);
request.CookieContainer = new CookieContainer();
request.CookieContainer.GetCookies(myURI);
HttpContext.Current.Response.AppendCookie(userInfo);
When debugging I got error on this line:
HttpContext.Current.Response.AppendCookie(userInfo);
telling that Response is null. Could you please tell me was that correct? How to add a new created cookie to the browser?
This error usually happens when you're trying to add a cookie outside of a web environment. You need to make sure you're doing this within a valid HTTP context, like in an MVC controller or an ASP.NET web page.
An example in an MVC controller:
If you're in a different context, like an ASPX page, you can use
Response.Cookies.Add(userInfo)instead ofResponse.SetCookie(userInfo).