开发者

getting username which is set in UserData of FormsAuthenticationTicket

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 sett开发者_高级运维ing 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


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.

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:

@User.Identity.Name

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 a NullReferenceException with this code.

As an alternative you could write a helper:

public static MvcHtmlString Username(this HtmlHelper htmlHelper)
{
    var identity = htmlHelper.ViewContext.HttpContext.User.Identity;
    if (identity.IsAuthenticated)
    {
        return MvcHtmlString.Create(identity.Name);
    }
    return MvcHtmlString.Empty;
}

which you could use like this:

@Html.Username()
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜