Roe*_*ens 1 c# identity entity-framework-core asp.net-core
我正在 ASP.NET Core 2.1 中开发应用程序。我正在将 Identity 与内置用户帐户一起使用。现在我正试图在这个应用程序中开发一个用户维护模块,我被卡住了。我无法获取控制器内的数据。这是我的代码:
ApplicationDbContext.cs:
public class ApplicationDbContext : IdentityDbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
public DbSet<ApplicationUser> ApplicationUsers { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
启动.cs:
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
services.AddIdentity<IdentityUser,IdentityRole>(config => {
config.SignIn.RequireConfirmedEmail = true;
})
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultUI()
.AddDefaultTokenProviders();
services.AddMemoryCache();
services.AddSession();
services.AddMvc()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
.AddSessionStateTempDataProvider();
services.AddSingleton<IEmailSender, EmailSender>();
}
Run Code Online (Sandbox Code Playgroud)
应用程序用户.cs:
public class ApplicationUser : IdentityUser
{
[Required]
public string FirstName { get; set; }
[Required]
public string Name { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
索引.cshtml:
@model IEnumerable<TestIdentity.Models.ApplicationUser>
@{
ViewData["Title"] = "Index";
}
<h2>Application users</h2>
@foreach (var item in Model)
{
<p>@item.Name</p>
}
Run Code Online (Sandbox Code Playgroud)
ApplicationUsersController.cs: :
public class ApplicationUsersController : Controller
{
private readonly ApplicationDbContext _context;
public ApplicationUsersController(ApplicationDbContext context)
{
_context = context;
}
// GET: Administrator/ApplicationUsers
public async Task<IActionResult> Index()
{
return View(await _context.ApplicationUsers.ToListAsync());
}
}
Run Code Online (Sandbox Code Playgroud)
_context.ApplicationUsers.ToListAsync() 没有返回任何结果,尽管我的 AspNetUsers 表中有数据。
如果您想ApplicationUser为您的 Identity使用 custom而不是 default IdentityUser。您需要在声明模型后进行一些更改。
1.在dbContext中:
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
Run Code Online (Sandbox Code Playgroud)
2.在startup.cs中:
services.AddIdentity<ApplicationUser,IdentityRole>(config => {
config.SignIn.RequireConfirmedEmail = true;
})
...
Run Code Online (Sandbox Code Playgroud)
3.在你的/Shared/_LoginPartial.cshtml
@inject SignInManager<ApplicationUser> SignInManager
@inject UserManager<ApplicationUser> UserManager
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2031 次 |
| 最近记录: |