5

Estou utilizando Visual Studio 2013, estou criando um novo projeto Asp.NET Web Application usando MVC e autenticação por "Conta de Usuário Individual".

Gostaria de saber como listar todos os usuários registrados.

Models:

IdentityModel

using Microsoft.AspNet.Identity.EntityFramework;

namespace WebApplication9.Models
{
    // You can add profile data for the user by adding more properties to your ApplicationUser class, please visit http://go.microsoft.com/fwlink/?LinkID=317594 to learn more.
    public class ApplicationUser : IdentityUser
    {
    }

    public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
        public ApplicationDbContext()
            : base("DefaultConnection")
        {
        }
    }
}

AccountViewModels

using System.ComponentModel.DataAnnotations;

namespace WebApplication9.Models
{
    public class ExternalLoginConfirmationViewModel
    {
        [Required]
        [Display(Name = "User name")]
        public string UserName { get; set; }
    }

    public class ManageUserViewModel
    {
        [Required]
        [DataType(DataType.Password)]
        [Display(Name = "Current password")]
        public string OldPassword { get; set; }

        [Required]
        [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
        [DataType(DataType.Password)]
        [Display(Name = "New password")]
        public string NewPassword { get; set; }

        [DataType(DataType.Password)]
        [Display(Name = "Confirm new password")]
        [Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match.")]
        public string ConfirmPassword { get; set; }
    }

    public class LoginViewModel
    {
        [Required]
        [Display(Name = "User name")]
        public string UserName { get; set; }

        [Required]
        [DataType(DataType.Password)]
        [Display(Name = "Password")]
        public string Password { get; set; }

        [Display(Name = "Remember me?")]
        public bool RememberMe { get; set; }
    }

    public class RegisterViewModel
    {
        [Required]
        [Display(Name = "User name")]
        public string UserName { get; set; }

        [Required]
        [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
        [DataType(DataType.Password)]
        [Display(Name = "Password")]
        public string Password { get; set; }

        [DataType(DataType.Password)]
        [Display(Name = "Confirm password")]
        [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
        public string ConfirmPassword { get; set; }
    }
}
2
  • 1
    Você consegue exibir uma lista qualquer com EntityFramework?
    – iuristona
    25/03/2014 às 14:52
  • Sim, eu consigo. 25/03/2014 às 16:02

1 Resposta 1

3

Se o contexto está mapeado corretamente, o seguinte Controller pode resolver:

public class UsuariosController : Controller
{
    public UserManager<ApplicationUser> UserManager { get; private set; }
    public RoleManager<IdentityRole> RoleManager { get; private set; }
    public MyDbContext context { get; private set; }

    public UsuariosController()
    {
        context = new MyDbContext();
        UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
        RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
    }

    public UsuariosController(UserManager<ApplicationUser> userManager, RoleManager<IdentityRole> roleManager)
    {
        UserManager = userManager;
        RoleManager = roleManager;
    }

    //
    // GET: /Users/
    public async Task<ActionResult> Index()
    {
        return View(await UserManager.Users.ToListAsync());
    }
}

O contexto deve ter a seguinte configuração:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);

    modelBuilder.Entity<IdentityUser>()
        .ToTable("Users");
    modelBuilder.Entity<ApplicationUser>()
        .ToTable("Users");
}

Verifique se sua solução já utiliza estes pacotes (packages.config). Se sim, experimente fechar a solution e abrir novamente.

  <package id="Microsoft.AspNet.Identity.Core" version="2.0.0-alpha1" targetFramework="net45" />
  <package id="Microsoft.AspNet.Identity.EntityFramework" version="2.0.0-alpha1" targetFramework="net45" />
  <package id="Microsoft.AspNet.Identity.Owin" version="2.0.0-alpha1" targetFramework="net45" />
  <package id="Microsoft.AspNet.Mvc" version="5.0.0" targetFramework="net45" />
  <package id="Microsoft.AspNet.Razor" version="3.0.0" targetFramework="net45" />
  <package id="Microsoft.AspNet.Web.Optimization" version="1.1.0" targetFramework="net45" />
  <package id="Microsoft.AspNet.WebPages" version="3.0.0" targetFramework="net45" />
  <package id="Microsoft.Owin" version="2.0.2" targetFramework="net45" />
  <package id="Microsoft.Owin.Host.SystemWeb" version="2.0.2" targetFramework="net45" />
  <package id="Microsoft.Owin.Security" version="2.0.2" targetFramework="net45" />
  <package id="Microsoft.Owin.Security.Cookies" version="2.0.2" targetFramework="net45" />
  <package id="Microsoft.Owin.Security.Facebook" version="2.0.2" targetFramework="net45" />
  <package id="Microsoft.Owin.Security.Google" version="2.0.2" targetFramework="net45" />
  <package id="Microsoft.Owin.Security.MicrosoftAccount" version="2.0.2" targetFramework="net45" />
  <package id="Microsoft.Owin.Security.OAuth" version="2.0.2" targetFramework="net45" />
  <package id="Microsoft.Owin.Security.Twitter" version="2.0.2" targetFramework="net45" />
  <package id="Microsoft.Web.Infrastructure" version="1.0.0.0" targetFramework="net45" />
  <package id="Owin" version="1.0" targetFramework="net45" />

Exemplo completo:

https://github.com/rustd/AspnetIdentitySample

17
  • Cigano, olha o erro retornado: 'Microsoft.AspNet.Identity.UserManager<WebApplication9.Models.ApplicationUser>' does not contain a definition for 'Users' and no extension method 'Users' accepting a first argument of type. 25/03/2014 às 16:11
  • A única alteração que fiz foi no contexto, o meu é ApplicationDBContext. 25/03/2014 às 16:12
  • 1
    Seu ApplicationUser deriva IdentityUser? Pode postar o código dos seus Models na pergunta? 25/03/2014 às 16:17
  • A ApplicationUser deriva de IdentityUser. Coloquei o código lá. 25/03/2014 às 16:31
  • 1
    Problema resolvido!!! Obrigado Cigano! 26/03/2014 às 18:26

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .