在Accountcontroller中设置cookie

本文关键字:cookie 设置 Accountcontroller | 更新日期: 2023-09-27 18:17:03

Response.Cookies.Add(新HttpCookie(FormsAuthentication.FormsCookieName,encTicket((;我使用了这段代码,但它返回的Object引用没有设置为对象的实例。有什么问题

您应该在构造函数之外创建cookie,这样您至少可以了解它抛出异常的原因。

通常,对于这样的事情,我会做以下操作:

// 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);

如果有什么不同的话,那至少可以让你找出导致空引用异常的原因,如果不能完全解决这个问题的话。

在Accountcontroller中设置cookie