How to make a user helper logged in to Asp.NET MVC 4?

Asked

Viewed 1,328 times

3

I need to implement a Helper for logged in user, ie a static class that returns information about the logged in user from context. The idea is to use the information both in Controllers how much in Views.

  • What would be a logged in user helper?

  • You need to give more details! What do you want the helper to do? And where will it consume data?

  • 3

    I need to get rich!

  • You are using Entity Framework?

2 answers

4


@Luiznegrini you can try using a Singleton in the Professionaluser class. Adding a static property of the same class type, when called you can search the current user through another external method and using as parameter the user id, encrypted, in a cookie or in the session.

namespace Aplicacao.Model
{
    public class ProfessionalUser
    {
        private static ProfessionalUser _user;
        private static string _keyUser = "idUserOuQualquerChaveQueVoceEscolher";

        public int IdProfessionalUser { get; set; }

        public string Email { get; set; }

        public string ReEmail { get; set; }

        public string Password { get; set; }

        public string RePassword { get; set; }

        public string Name { get; set; }

        public int IdProfessionalRegister { get; set; }

        public string City { get; set; }

        public string State { get; set; }

        public int Phone { get; set; }

        public static ProfessionalUser UsuarioAtual
        {
            get
            {
                if(_user == null)
                {
                    int idUser = 0;
                    HttpCookie cookie = HttpContext.current.Request.Cookies[_keyUser];
                    string v = cookie != null ? cookie.Value : String.Empty;
                    int.TryParse(v, out idUser);
                    _user = (new QualquerGerenciadorDeUsuario()).FuncaoQuePegaOUsuarioPeloID(idUser);
                }
                return _user;
            }
            set
            {
                int idUser = 0;
                if(value != null && value.ID > 0)
                {
                    idUser = value.ID;
                    _user = value;
                }else
                    _user = null;

                HttpCookie cookie = new HttpCookie(_keyUser, idUser.ToString());
                HttpContext cxt = HttpContext.current;
                cookie.Expires = DateTime.Today.AddHours(3);// o cookie vale por 3 horas
                cxt.Response.Cookies.Add(cookie);
            }
        }
    }
}

Already in the View, you can call the property at any time two ways:

@Aplicacao.Model.ProfessionalUser.UsuarioAtual

And from there you can take any and all property of the current user:

@Aplicacao.Model.ProfessionalUser.UsuarioAtual.IdProfessionalUser

The other way is by including the namespace in View:

@using Aplicacao.Model
@ProfessionalUser.UsuarioAtual

... and the properties are the same:

@ProfessionalUser.UsuarioAtual.IdProfessional

I hope it helped.

Att, Uilque Messias

2

Follows a Helper I did to get logged in user information.

This project uses Membership, that is, it is an old approach, but serves as an example for improvements in the case of ASP.NET Identity:

public static class LoggedUserHelper
{
    private static MyProjectContext context = new MyProjectContext();

    public static UserProfile CurrentUserInfo(IPrincipal User) {
        int currentUserId = WebSecurity.GetUserId(User.Identity.Name);
        return context.UserProfile.AsNoTracking().SingleOrDefault(x => x.UserId == currentUserId);
    }

    public static int UserId(IPrincipal User) {
        return WebSecurity.GetUserId(User.Identity.Name);
    }

    public static int UserId(String UserName) {
        return WebSecurity.GetUserId(UserName);
    }

    ...
}

Obviously my Model UserProfile has several additional columns, but I will put only the minimum needed to work:

public class UserProfile {
    [Key]
    public int UserId { get; set; }

    ...
}
  • "Myprojectcontext" would be the Datacontext of the project itself? It was not clear, what should I do.

  • 1

    @Luiznegrini. In fact what Helper does is gather a bunch of commands together that you would have to invoke to get data from a user, not just from the log-in. It may belong to other users, including.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.