programing

ASP.NET에서 영구 쿠키를 만들려면 어떻게 해야 합니까?

closeapi 2023. 6. 20. 21:38
반응형

ASP.NET에서 영구 쿠키를 만들려면 어떻게 해야 합니까?

다음 줄로 쿠키를 만들고 있습니다.

HttpCookie userid = new HttpCookie("userid", objUser.id.ToString());
userid.Expires.AddYears(1);
Response.Cookies.Add(userid);

어떻게 하면 지속적으로 유지할 수 있을까요?

브라우저를 닫은 후 동일한 페이지를 다시 방문하면 다시 찾을 수 없습니다.

그렇게 하는 방법은 다음과 같습니다.

영구 쿠키를 쓰는 중입니다.

//create a cookie
HttpCookie myCookie = new HttpCookie("myCookie");

//Add key-values in the cookie
myCookie.Values.Add("userid", objUser.id.ToString());

//set cookie expiry date-time. Made it to last for next 12 hours.
myCookie.Expires = DateTime.Now.AddHours(12);

//Most important, write the cookie to client.
Response.Cookies.Add(myCookie);

영구 쿠키를 읽는 중입니다.

//Assuming user comes back after several hours. several < 12.
//Read the cookie from Request.
HttpCookie myCookie = Request.Cookies["myCookie"];
if (myCookie == null)
{
    //No cookie found or cookie expired.
    //Handle the situation here, Redirect the user or simply return;
}

//ok - cookie is found.
//Gracefully check if the cookie has the key-value as expected.
if (!string.IsNullOrEmpty(myCookie.Values["userid"]))
{
    string userId = myCookie.Values["userid"].ToString();
    //Yes userId is found. Mission accomplished.
}

승인된 답변은 맞지만, 원래 코드가 작동하지 않은 이유는 명시되어 있지 않습니다.

질문의 잘못된 코드:

HttpCookie userid = new HttpCookie("userid", objUser.id.ToString());
userid.Expires.AddYears(1);
Response.Cookies.Add(userid);

두 번째 줄을 보세요.만료 기준은 기본값 1/1/0001을 포함하는 Expires 속성에 있습니다.위의 코드는 1/1/0002로 평가되고 있습니다.또한 평가가 다시 속성에 저장되지 않습니다.대신 Expires 속성을 현재 날짜의 기준으로 설정해야 합니다.

수정된 코드:

HttpCookie userid = new HttpCookie("userid", objUser.id.ToString());
userid.Expires = DateTime.Now.AddYears(1);
Response.Cookies.Add(userid);

FWIW는 암호화되지 않은 쿠키에 사용자 ID와 같은 것을 저장할 때 매우 주의해야 합니다.이렇게 하면 사용자가 다른 사용자로 가장할 수 있는 쿠키 중독이 발생하기 쉽습니다.만약 당신이 이와 같은 것을 고려하고 있다면, 저는 인증 쿠키 양식을 직접 사용하는 것을 강력히 추천합니다.

bool persist = true;

var cookie = FormsAuthentication.GetAuthCookie(loginUser.ContactId, persist);

cookie.Expires = DateTime.Now.AddMonths(3);

var ticket = FormsAuthentication.Decrypt(cookie.Value);

var userData = "store any string values you want inside the ticket
                 extra than user id that will be encrypted"

var newTicket = new FormsAuthenticationTicket(ticket.Version, ticket.Name,
     ticket.IssueDate, ticket.Expiration, ticket.IsPersistent, userData);

cookie.Value = FormsAuthentication.Encrypt(newTicket);

Response.Cookies.Add(cookie);

그런 다음 ASP.NET 페이지에서 언제든지 다음을 수행하여 이 페이지를 읽을 수 있습니다.

string userId = null;
if (this.Context.User.Identity.IsAuthenticated) 
{
    userId = this.Context.User.Identity.Name;
}

ASP.NET 인증을 사용하고 쿠키를 영구적으로 설정하려면 양식을 설정해야 합니다.인증Ticket.IsPersistent = true 이것이 주요 아이디어입니다.

bool isPersisted = true;
var authTicket = new FormsAuthenticationTicket(
1,
user_name, 
DateTime.Now,
DateTime.Now.AddYears(1),//Expiration (you can set it to 1 year)
isPersisted,//THIS IS THE MAIN FLAG
addition_data);
    HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, authTicket );
    if (isPersisted)
        authCookie.Expires = authTicket.Expiration;

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

이것을 마지막 줄로 추가해야 합니다.

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

쿠키 값을 읽어야 하는 경우 다음과 유사한 방법을 사용합니다.

    string cookieUserID= String.Empty;

    try
    {
        if (HttpContext.Current.Request.Cookies["userid"] != null)
        {
            cookieUserID = HttpContext.Current.Request.Cookies["userid"];
        }
    }
    catch (Exception ex)
    {
       //handle error
    }

    return cookieUserID;

//쿠키 추가

var panelIdCookie = new HttpCookie("panelIdCookie");
panelIdCookie.Values.Add("panelId", panelId.ToString(CultureInfo.InvariantCulture));
panelIdCookie.Expires = DateTime.Now.AddMonths(2); 
Response.Cookies.Add(panelIdCookie);

//쿠키 읽기

    var httpCookie = Request.Cookies["panelIdCookie"];
                if (httpCookie != null)
                {
                    panelId = Convert.ToInt32(httpCookie["panelId"]);
                }

언급URL : https://stackoverflow.com/questions/3140341/how-can-i-create-persistent-cookies-in-asp-net

반응형