3
votes

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

1
I'm pretty sure storing id as a static variable will cause you problems. Make it into a property instead.Jesse Buchanan
@jbinto that's an inaccurate statement since the op has the value of id bound to a the contextual instance at run time through the HttpContext.Current object. With the way @raklos has this coded you can gaurentee at run time you will access the id only for the current request, if you are in a state that does not have access to HttpContext.Current you will get a null reference error.Chris Marisic

1 Answers

1
votes

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()