【发布时间】:2021-09-06 15:41:04
【问题描述】:
这些是我在 Controller 中的代码:
public class IdentityUserController : Controller
{
private readonly UserManager<DatabaseContext> _um;
private readonly SignInManager<DatabaseContext> _sm;
[HttpGet]
public IActionResult Login()
{
return View();
}
[HttpPost]
public async Task<IActionResult> Login( Models.Person lc)
{
if (ModelState.IsValid)
{
var result = await _sm.PasswordSignInAsync(lc.NationalCode, lc.Password, false, true);
if (result.Succeeded)
{
TempData["LoggedUserCode"] = lc.NationalCode;
ViewBag.LoggeduserDetails = lc.Name + " " + lc.Family;
return RedirectToAction("Index","Home");
}
ModelState.AddModelError("", "User or Password not valid");
}
return View(lc);
}
}
这些是启动配置中的代码:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddDbContext<DatabaseContext>(option => option.UseSqlServer(@"Data Source =. ; Initial Catalog = LeaveSheet; Integrated Security=True;MultipleActiveResultSets=true "));
services.ConfigureApplicationCookie(option => option.LoginPath = "/IdentityUser/Login");
}
当我运行它时,提交后登录视图中出现以下错误:
NullReferenceException:对象引用未设置为对象的实例。
-
IdentityUserController.cs 中的LeaveSheet.Controllers.IdentityUserController.Login(Person lc)
var result = await _sm.PasswordSignInAsync(lc.NationalCode, lc.Password, false, true);
Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor+TaskOfIActionResultExecutor.Execute(IActionResultTypeMapper 映射器,ObjectMethodExecutor 执行器,对象控制器,对象[] 参数) System.Threading.Tasks.ValueTask.get_Result() System.Runtime.CompilerServices.ValueTaskAwaiter.GetResult() Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.g__Awaited|12_0(ControllerActionInvoker 调用程序,ValueTask actionResultValueTask) Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.g__Awaited|10_0(ControllerActionInvoker 调用者,Task lastTask,State next,Scope 范围,对象状态,bool isCompleted) *
**你能帮帮我吗**
【问题讨论】:
-
您的
DatabaseContext中有以下构造函数吗?public DatabaseContext(DbContextOptions<DatabaseContext> options) : base(options) { }如果没有,请添加。 -
这个案子有更新吗?
-
你好银秋谢谢你的回复----我添加了你建议的构造函数----现在我得到了这个错误我调用操作登录时的运行时间 --------- InvalidOperationException:尝试时无法解析类型“Microsoft.AspNetCore.Identity.UserManager`1[LeaveSheet.Models.Context.DatabaseContext]”的服务激活“LeaveSheet.Controllers.IdentityUserController”。 Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, bool isDefaultParameterRequired)
-
建议大家学习Identity in asp.net core
-
首先,你的DatabaseContext应该继承
IdentityDbContext,然后你的控制器应该是private readonly UserManager<IdentityUser> _um; private readonly SignInManager<IdentityUser> _sm;,然后在你的启动中应该添加services.AddDefaultIdentity<IdentityUser>() .AddEntityFrameworkStores<DatabaseContext>();
标签: asp.net-mvc asp.net-core constructor asp.net-identity dbcontext