0

Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket)); i use this code but it return Object reference not set to an instance of an object. what is the wrong with it

tereško
  • 56,151
  • 24
  • 92
  • 147
  • Duplicate of [What is a NullReferenceException and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Jashaszun Aug 07 '14 at 16:18

1 Answers1

0

You should be creating the cookie outside of the constructor, so you can at least discern why it's throwing the exception.

Typically for something like this I would do the following :

// create the auth cookie with the domain you've specified
var cookie = new HttpCookie(FormsAuthentication.FormsCookieName)
{
    Domain = FormsAuthentication.CookieDomain;
};

// create the auth ticket and encrypt it 
var authTicket = new FormsAuthenticationTicket(1, "USERS_EMAIL_OR_USERNAME", DateTime.Now, DateTime.Now.AddHours(24), true, "ANY_USER_INFO_THAT_SHOULD_GO_INTO_THE_COOKIE");
var encryptedTicket = FormsAuthentication.Encrypt(authTicket);

// set the cookie value to the encrypted ticket
cookie.Value = encryptedTicket;

// now, add it to the response, but remove the old one in case it's still there
Response.Cookies.Remove(FormsAuthentication.FormsCookieName);
Response.Cookies.Add(cookie);

If anything, that will at least allow you to find out what's causing your null reference exception, if not fix the issue entirely.

X3074861X
  • 3,539
  • 4
  • 28
  • 44