Create and add cookie by c# in .net framework 4.8 does not work

77 Views Asked by At

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?

1

There are 1 best solutions below

6
Otavio Salomão Ferreira On

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:

public class MyController : Controller
{
    public ActionResult Index()
    {
        HttpCookie userInfo = new HttpCookie("userInfo");
        userInfo["userName"] = "user1";
        userInfo["logdata"] = "data1";
        userInfo.Expires = DateTime.Now.AddMinutes(1);

        Response.SetCookie(userInfo);

        return View();
    }
}

If you're in a different context, like an ASPX page, you can use Response.Cookies.Add(userInfo) instead of Response.SetCookie(userInfo).