如何存储在ASP.NET成员的Cookie的自定义数据 [英] How to store custom data in ASP.NET Membership Cookie
问题描述
谁能给我一个例子(或点我在正确的方向)如何存储在一个ASP.NET成员的cookie自定义数据?
我要像用户名和URLSlug一些自定义属性添加到Cookie,并能够检索以同样的方式人会获得用户名信息。
修改
我用code诗人的例子,用下面的走了过来。
当我设置为断点昏暗SerializedUser的String = SerializeUser(用户数据)
的值用户数据
是正确的。它拥有所有我希望它具有的属性。
我现在运行到的问题是,当我到昏暗的用户数据作为字符串= authTicket.UserData code>(断点),该值
,
。我很想弄清楚我在做什么错。
这里的code。
进口系统
进口的System.Web
进口System.Web.Security命名空间Utilities.Authentication
公共NotInheritable类CustomAuthentication
私人小组新的()
结束小组 公共共享功能CreateAuthCookie(BYVAL用户名作为字符串,BYVAL用户数据作为Domain.Models.UserSessionModel,持续BYVAL由于布尔)作为的HttpCookie 昏暗的发行为DATETIME = DateTime.Now
''#formsAuth不公开超时!?有破解绕
''#宠坏的部件和保持运动..
昏暗fooCookie作为的HttpCookie = FormsAuthentication.GetAuthCookie(富,真)
昏暗formsTimeout作为整数= Convert.ToInt32((fooCookie.Expires - DateTime.Now).TotalMinutes) 昏暗的到期为DATETIME = DateTime.Now.AddMinutes(formsTimeout)
昏暗cookiePath作为字符串= FormsAuthentication.FormsCookiePath 昏暗SerializedUser作为字符串= SerializeUser(用户数据) 昏暗的票=新的FormsAuthenticationTicket(0,用户名,发行,到期,真实,SerializedUser,cookiePath)
返回CreateAuthCookie(门票,有效期,持久)
结束功能 公共共享功能CreateAuthCookie(BYVAL票作为的FormsAuthenticationTicket,BYVAL到期为DATETIME,持续BYVAL由于布尔)作为的HttpCookie
昏暗creamyFilling作为字符串= FormsAuthentication.Encrypt(票)
点心饼干=新的HttpCookie(FormsAuthentication.FormsCookieName,creamyFilling)随着{_
。域= FormsAuthentication.CookieDomain,_
。路径= FormsAuthentication.FormsCookiePath _
}
如果再持续
cookie.Expires =到期
万一 返回的cookie
结束功能
公共共享功能RetrieveAuthUser()作为Domain.Models.UserSessionModel
昏暗cookieName作为字符串= FormsAuthentication.FormsCookieName
昏暗authCookie作为的HttpCookie = HttpContext.Current.Request.Cookies(cookieName)
昏暗authTicket作为的FormsAuthenticationTicket = FormsAuthentication.Decrypt(authCookie.Value)
昏暗用户数据作为字符串= authTicket.UserData 昏暗usersessionmodel作为新Domain.Models.UserSessionModel
usersessionmodel = DeserializeUser(用户数据)
返回usersessionmodel
结束功能
私人共享功能SerializeUser(BYVAL usersessionmodel作为Domain.Models.UserSessionModel)作为字符串
昏暗BF作为新Runtime.Serialization.Formatters.Binary.BinaryFormatter()
昏暗的纪念品作为新IO.MemoryStream
bf.Serialize(MEM,usersessionmodel)
返回Convert.ToBase64String(mem.ToArray())
结束功能 私人共享功能DeserializeUser(BYVAL serializedusersessionmodel作为字符串)作为Domain.Models.UserSessionModel
昏暗BF作为新Runtime.Serialization.Formatters.Binary.BinaryFormatter()
昏暗纪念品作为新IO.MemoryStream(Convert.FromBase64String(serializedusersessionmodel))
返回DirectCast(bf.Deserialize(MEM),Domain.Models.UserSessionModel)
结束功能
末级
最终命名空间
下面就是我创造一切的魔力。这种方法在继承了BaseController级 System.Web.Mvc.Controller
受保护的覆盖功能CreateActionInvoker()作为System.Web.Mvc.IActionInvoker 如果User.Identity.IsAuthenticated然后''#这if语句最终也将检查以确保该Cookie确实存在。 昏暗sessionuser作为Domain.Models.UserSessionModel =新Domain.Models.UserSessionModel(OpenIdService.GetOpenId(HttpContext.User.Identity.Name)。用户)
HttpContext.Response.Cookies.Add(UrbanNow.Core.Utilities.Authentication.CustomAuthentication.CreateAuthCookie(HttpContext.User.Identity.Name, sessionuser,真))
万一
结束功能
和这里是我如何努力和检索信息。
昏暗用户作为Domain.Models.UserSessionModel = CustomAuthentication.RetrieveAuthUser
根据不同的场景中,使用一个单独的cookie的可能的是一个可行的选择,但在我看来是有几个原因,包括次优简单的事实,你必须要管理多个cookie以及管理cookie的有效期。
有关合并的自定义信息到你的表单票最可靠的策略是利用门票的用户数据
字段。这正是它的存在些什么。
您可以轻松地存储自定义数据在机票的用户数据
字段。
有一些关注要注意有关的数据的尺寸的要被存储在被说明的车票<一href=\"http://stackoverflow.com/questions/2381028/issues-with-storing-the-custom-principal-in-session-for-asp-net-mvc/2385173#2385173\">here
和<一个href=\"http://stackoverflow.com/questions/996588/how-to-set-asp-net-authenticated-properties/2357892#2357892\">here是一个小的类,它可以在存储表单自定义的车票数据的任务有所帮助。
Can anyone give me an example (or point me in the right direction) on how to store custom data in an ASP.NET Membership cookie?
I need to add some custom properties like UserID and URLSlug to the cookie and be able to retrieve the information in the same way one would retrieve the Username.
Edit:
I used Code Poet's example and came up with the following.
When I set a breakpoint at Dim SerializedUser As String = SerializeUser(userData)
the value of userData
is right. It has all the properties I expect it to have.
The problem I'm now running into is that when I get to Dim userdata As String = authTicket.UserData
(breakpoint), the value is ""
. I'd love to figure out what I'm doing wrong.
Here's the code.
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
Here's where I create all the magic. This method is in a "BaseController" class that inherits System.Web.Mvc.Controller
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
And here's how I try and retrieve the info.
Dim user As Domain.Models.UserSessionModel = CustomAuthentication.RetrieveAuthUser
Depending on the scenario, using a separate cookie might be a viable option, but in my opinion is sub optimal for several reasons including the simple fact that you have to manage multiple cookies as well as managing the lifetime of the cookie.
The most reliable strategy for incorporating custom information into your forms ticket is to leverage the userData
field of the ticket. That is exactly what it is there for.
You can easily store custom data in the userData
field of the ticket.
There are a few concerns to be aware of regarding the size of the data to be stored in the ticket that are explained here
And here is a small class that can help in the task of storing custom data in your forms ticket.
这篇关于如何存储在ASP.NET成员的Cookie的自定义数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!