【发布时间】:2017-09-19 15:04:15
【问题描述】:
我正在尝试将 ASP.NET Identity 3.0 单用户身份验证添加到 Visual Studio 2017 中的“ASP.NET Core Application Angular 模板”。我在这里创建了一个 GitHub 存储库:
https://github.com/DapperDanH/NutmegStackoverflow
这个项目真的没有太多。从高层次来看,这就是我所做的:
- 使用 .NET Core 和 ASP.NET Core 2.0 创建了一个新的“ASP.NET Core Web 应用程序”,并在 Visual Studio 中选择了 Angular 模板。
- 我从现有数据库中添加了 ASP.Identity、EF Core 和脚手架代码优先文件。
- 我使用“个人用户帐户”示例项目使用 Web 应用程序模板从“ASP.NET Core Web 应用程序”复制并粘贴了许多控制器和视图。
- 我修改了 Startup.cs(添加了 service.AddIdentity 和 app.UseAuthentication() 等)
我的目标是对身份验证部分使用标准的 ASP.NET MVC。
似乎一切正常。 Web 应用程序启动并显示主页。我创建了指向“注册”和“登录”页面的链接。我可以成功注册一个新用户并将新用户添加到数据库中。用户可以在登录页面输入自己的信息,AccountController.Login方法返回成功给PasswordSignInAsync方法:
var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure: false);
问题是,没有创建身份验证 cookie。好吧,大约 99% 的时间没有创建 cookie,但时不时会创建一个。
我的直觉说问题可能出在 Startup.cs 中。这是我正在使用的代码:
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<NutmegContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddIdentity<User, AppRole>()
.AddEntityFrameworkStores<NutmegContext>()
.AddDefaultTokenProviders();
// Add application services.
services.AddTransient<IEmailSender, EmailSender>();
services.AddMvc();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions
{
HotModuleReplacement = true
});
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseAuthentication();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
routes.MapSpaFallbackRoute(
name: "spa-fallback",
defaults: new { controller = "Home", action = "Index" });
});
}
我真的希望有人可以帮助我。要查看实际情况:
- 在此处下载项目:https://github.com/DapperDanH/NutmegStackoverflow
- 在包管理器控制台中运行 Update-Database,确保默认项目是 Nutmeg.Data。
- 运行应用程序,确保 Nutmeg.Web 是启动项目。
- 单击注册按钮并注册一个新用户。检查数据库并注意已添加用户。
- 点击登录。输入步骤 4 中使用的相同信息。是否创建了 cookie?
希望有人可以帮助我。感谢您阅读这篇长文!
谢谢, 丹
【问题讨论】:
-
我能够让应用程序始终如一地创建身份验证 cookie,但将我的 Web 项目切换到 HTTPS。我不知道为什么这很重要,但它似乎可以解决它。谁能解释一下?
标签: entity-framework asp.net-core-2.0 asp.net-identity-3