我正在尝试使用Identity包获取当前用户(执行该方法的用户(的id。上下文是UserManager<应用程序用户>(ApplicationUser是IdentityUser(。
var currentUserId = User.FindFirst(ClaimTypes.NameIdentifier).Value;
当用户登录时,我会将其添加到声明列表中。"user"是DB中的ApplicationUser。
new Claim(ClaimTypes.NameIdentifier, user.Id),
我还使用了这个文档,并在Program.cs.中添加了以下内容
builder.Services.Configure<IdentityOptions>(options =>
options.ClaimsIdentity.UserIdClaimType = ClaimTypes.NameIdentifier);
然而,我一直得到一个";System.NullReferenceException:"对象引用未设置为对象的实例。"错误
链接还显示我可以将当前用户作为
var user = await userManager.GetUserAsync(User);
然而,这只是使用户为null。
我正在使用poster/swagger进行调试。
以下是整个堆栈跟踪:
System.NullReferenceException: Object reference not set to an instance of an object.
at Server.Authentication.Controllers.AuthController.UpdateUser(String id, UpdateModel model) in C:i2PromoCreatepromocreateServerAuthenticationControllersAuthController.cs:line 168
at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.TaskOfIActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeActionMethodAsync>g__Awaited|12_0(ControllerActionInvoker invoker, ValueTask`1 actionResultValueTask)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeNextActionFilterAsync>g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
--- End of stack trace from previous location ---
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|20_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
有人能告诉我我做错了什么吗?
我在回答我自己的问题。我只需要方法上方的[Authorize]属性。