获取在 FormsAuthenticationTicket 的 UserData 中设置的用户名
我正在考虑使用我的观点(Razor 语法)来获取我的网站的用户名:
@MySite.Helpers.Utils.UserName
这是 utils 类:
public class Utils
{
static FormsIdentity id = (FormsIdentity)HttpContext.Current.User.Identity;
public static string UserName { get { return id.Ticket.UserData; } }
}
这段代码有任何潜在的问题吗?
我这样做的原因是因为当用户登录时我将在新 FormsAuthenticationTicket 的 userdata 字段中存储用户名。
我这样处理它是因为我使用 facebook connect 并希望将 ID 存储在用户名字段中在数据库中,他们的用户名/全名在单独的表中。
所以我处理 Facebook 用户名和我的网站注册用户名的逻辑需要以不同的方式处理。登录后,我考虑在那里处理它,然后将 userdata 设置为实际用户名。
因此,在整个网站中,我可以使用以下方式获取登录的用户名:@MySite.Helpers.Utils.UserName
这听起来不错吗?它是静态变量这一事实会成为问题吗?
或者有更好的方法来管理这个吗?也许是会话变量?
谢谢
Im thinking of getting usernames of my site using this in my view(Razor syntax):
@MySite.Helpers.Utils.UserName
heres the utils class:
public class Utils
{
static FormsIdentity id = (FormsIdentity)HttpContext.Current.User.Identity;
public static string UserName { get { return id.Ticket.UserData; } }
}
Are there any potential problems with this code?
The reason Im doing it like this is because Im going to store username in the userdata field of a new FormsAuthenticationTicket when the user logs in.
I'm handling it like this because Im using facebook connect and want to store there ID in the username field in the db and their usernames/fullnames in a separate table.
so my logic to handle facebook usernames and my site registered usernames needs to be handled differently. Upon login Im thinking of handling it there then setting userdata as the actual username.
therefore throughout the site i can just get the logged in users name using : @MySite.Helpers.Utils.UserName
does this sound ok? will the fact that its a static variable be an issue?
or is there a better way to manage this? session variables maybe?
thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当前登录用户的用户名已存储在身份验证 cookie 中。您不需要再次将其存储在 UserData 中。为了在 Razor 模板中检索它,您可以简单地:
显然,建议使用
[Authorize]
属性装饰渲染此视图的控制器操作,以确保用户在访问它之前经过身份验证,或者使用此代码您可能会收到NullReferenceException
。作为替代方案,您可以编写一个助手:
您可以像这样使用它:
The username of the currently logged in user is already stored in the authentication cookie. You don't need to store it once again in the UserData. And in order to retrieve it in your Razor template you could simply:
Obviously it is recommended to decorate the controller action rendering this view with the
[Authorize]
attribute to ensure that a user is authenticated before accessing it or you might get aNullReferenceException
with this code.As an alternative you could write a helper:
which you could use like this: