gpt4 book ai didi

asp.net - 如何在 ASP.NET Membership Cookie 中存储自定义数据

转载 作者:行者123 更新时间:2023-12-04 22:52:03 25 4
gpt4 key购买 nike

谁能给我一个关于如何在 ASP.NET Membership cookie 中存储自定义数据的示例(或指出正确的方向)?

我需要向 cookie 添加一些自定义属性,如 UserID 和 URLSlug,并且能够以与检索用户名相同的方式检索信息。

编辑:

我使用了 Code Poet 的示例并提出了以下内容。

当我在 Dim SerializedUser As String = SerializeUser(userData) 处设置断点时userData的值是对的。它具有我期望的所有特性。

我现在遇到的问题是,当我到达 Dim userdata As String = authTicket.UserData 时(断点),值为"" .我很想弄清楚我做错了什么。

这是代码。

Imports System
Imports System.Web
Imports System.Web.Security

Namespace Utilities.Authentication
Public NotInheritable Class CustomAuthentication
Private Sub New()
End Sub

Public Shared Function CreateAuthCookie(ByVal userName As String, ByVal userData As Domain.Models.UserSessionModel, ByVal persistent As Boolean) As HttpCookie

Dim issued As DateTime = DateTime.Now
''# formsAuth does not expose timeout!? have to hack around the
''# spoiled parts and keep moving..
Dim fooCookie As HttpCookie = FormsAuthentication.GetAuthCookie("foo", True)
Dim formsTimeout As Integer = Convert.ToInt32((fooCookie.Expires - DateTime.Now).TotalMinutes)

Dim expiration As DateTime = DateTime.Now.AddMinutes(formsTimeout)
Dim cookiePath As String = FormsAuthentication.FormsCookiePath

Dim SerializedUser As String = SerializeUser(userData)

Dim ticket = New FormsAuthenticationTicket(0, userName, issued, expiration, True, SerializedUser, cookiePath)
Return CreateAuthCookie(ticket, expiration, persistent)
End Function

Public Shared Function CreateAuthCookie(ByVal ticket As FormsAuthenticationTicket, ByVal expiration As DateTime, ByVal persistent As Boolean) As HttpCookie
Dim creamyFilling As String = FormsAuthentication.Encrypt(ticket)
Dim cookie = New HttpCookie(FormsAuthentication.FormsCookieName, creamyFilling) With { _
.Domain = FormsAuthentication.CookieDomain, _
.Path = FormsAuthentication.FormsCookiePath _
}
If persistent Then
cookie.Expires = expiration
End If

Return cookie
End Function


Public Shared Function RetrieveAuthUser() As Domain.Models.UserSessionModel
Dim cookieName As String = FormsAuthentication.FormsCookieName
Dim authCookie As HttpCookie = HttpContext.Current.Request.Cookies(cookieName)
Dim authTicket As FormsAuthenticationTicket = FormsAuthentication.Decrypt(authCookie.Value)
Dim userdata As String = authTicket.UserData

Dim usersessionmodel As New Domain.Models.UserSessionModel
usersessionmodel = DeserializeUser(userdata)
Return usersessionmodel
End Function


Private Shared Function SerializeUser(ByVal usersessionmodel As Domain.Models.UserSessionModel) As String
Dim bf As New Runtime.Serialization.Formatters.Binary.BinaryFormatter()
Dim mem As New IO.MemoryStream
bf.Serialize(mem, usersessionmodel)
Return Convert.ToBase64String(mem.ToArray())
End Function

Private Shared Function DeserializeUser(ByVal serializedusersessionmodel As String) As Domain.Models.UserSessionModel
Dim bf As New Runtime.Serialization.Formatters.Binary.BinaryFormatter()
Dim mem As New IO.MemoryStream(Convert.FromBase64String(serializedusersessionmodel))
Return DirectCast(bf.Deserialize(mem), Domain.Models.UserSessionModel)
End Function
End Class
End Namespace

这就是我创造所有魔法的地方。此方法位于继承 System.Web.Mvc.Controller 的“BaseController”类中。
Protected Overrides Function CreateActionInvoker() As System.Web.Mvc.IActionInvoker

If User.Identity.IsAuthenticated Then ''# this if statement will eventually also check to make sure that the cookie actually exists.

Dim sessionuser As Domain.Models.UserSessionModel = New Domain.Models.UserSessionModel(OpenIdService.GetOpenId(HttpContext.User.Identity.Name).User)
HttpContext.Response.Cookies.Add(UrbanNow.Core.Utilities.Authentication.CustomAuthentication.CreateAuthCookie(HttpContext.User.Identity.Name, sessionuser, True))
End If
End Function

这是我尝试检索信息的方法。
 Dim user As Domain.Models.UserSessionModel = CustomAuthentication.RetrieveAuthUser

最佳答案

首先,ASP.Net Membership 提供者不写任何 cookie,身份验证 cookie 是由 FormsAuthentication 编写的。

其次,为什么要干涉身份验证 cookie。您可以完全在单独的 cookie 中执行此操作。以下是您如何做到这一点。

将键值写入 cookie。

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

//Add key-values in the cookie
myCookie.Values.Add("UserId", "your-UserId");
myCookie.Values.Add("UrlSlug", "your-UrlSlug");

//set cookie expiry date-time, if required. 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);

从 cookie 中读取键值。
//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.
}

if (!string.IsNullOrEmpty(myCookie.Values["UrlSlug"]))
{
string UrlSlug = myCookie.Values["UrlSlug"].ToString();
//Yes key2 is found. Mission accomplished.
}

If at all you need to disturb the authentication cookie, though not advisable, This is how you may do it.



将键值写入 cookie。
//create a cookie
HttpCookie myCookie = FormsAuthentication.GetAuthCookie("UserName", true);

//Add key-values in the cookie
myCookie.Values.Add("UserId", "your-UserId");
myCookie.Values.Add("UrlSlug", "your-UrlSlug");

//set cookie expiry date-time, if required. 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);

从 cookie 中读取键值。
//Assuming user comes back after several hours. several < 12.
//Read the cookie from Request.
HttpCookie myCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
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.
}

if (!string.IsNullOrEmpty(myCookie.Values["UrlSlug"]))
{
string UrlSlug = myCookie.Values["UrlSlug"].ToString();
//Yes key2 is found. Mission accomplished.
}

关于asp.net - 如何在 ASP.NET Membership Cookie 中存储自定义数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3243896/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com