在 ASP.NET 成员资格中存储和访问旧用户 ID
我有一个旧的 UserID (int32),我希望将其链接到 asp.net 会员资格。我已经在数据库上设置了链接表,我对此部分感到满意。问题是在 Web 应用程序中将 UserID 存储在哪里,以便在需要时可以轻松访问。
我决定存储它的最佳位置是登录控件的 LoggedIn 事件中 FormsAuthenticationTicket 的 UserData 部分。我第一次尝试使其可访问,是将其提取到 BasePage 类的 PreInit 中。这样做的问题是,当 UserControls 需要 UserID 时,它会变得混乱。
将其包装在实用程序类中的静态方法或属性中是否可以接受,如下所示:
public static int UserID
{
get
{
int userID = 0;
if (HttpContext.Current.User.Identity is FormsIdentity)
{
FormsIdentity id = (FormsIdentity)HttpContext.Current.User.Identity;
FormsAuthenticationTicket ticket = id.Ticket;
userID = Int32.Parse(ticket.UserData);
}
return userID;
}
}
这似乎有效,但我不知道我是否在这里违反了一些不成文的规则。我认为所有这些东西都在内存中,因此这种访问没有很大的开销。
I have a legacy UserID (int32) which I wish to link to asp.net membership. I have set up link tables on the database and I'm happy with that part. The question is where to store the UserID in the web application so that it is easily accessible when required.
I decided that the best place to store it is in the UserData part of the FormsAuthenticationTicket in the LoggedIn event of the Login Control. My first attempt to make this accessible was to extract it in the PreInit of my BasePage class. The trouble with this is that it gets messy when the UserID is required by UserControls.
Is it acceptable to just wrap it in a static method or property in a Utilities class, something like this:
public static int UserID
{
get
{
int userID = 0;
if (HttpContext.Current.User.Identity is FormsIdentity)
{
FormsIdentity id = (FormsIdentity)HttpContext.Current.User.Identity;
FormsAuthenticationTicket ticket = id.Ticket;
userID = Int32.Parse(ticket.UserData);
}
return userID;
}
}
This seems to work but I don't know if I'm breaking some unwritten rule here. I presume all this stuff is in memory so there's no great overhead in this access.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
从功能角度来看,您的代码看起来不错(尽管我会稍微清理一下,但这更多是一种风格)。
不过,您可能会考虑将其作为扩展方法,而不是仅仅将其放在随机实用程序类中。也许是
IIdentity
类的扩展?我想,使用 UserData 字段就可以了。另一种选择是使用自定义
Ticket
创建您自己的IIdentity
对象,并将它们包装在GenericPrincipal
中 - 对于您来说可能工作量太大不过,我们在追赶。Your code looks fine from a functional perspective (though I would clean it up a bit, but that's more a style thing).
You might consider making it an extension method, though, rather than just sticking it in a random utility class. Maybe an extension for the
IIdentity
class?Using the
UserData
field is fine, I guess. Another option is to create your ownIIdentity
object with a customTicket
and wrap them in aGenericPrincipal
-- might be too much work for what you're after, though.