在Entity Framework Core中获取当前用户ID的正确方法 [英] Proper way to get current User ID in Entity Framework Core

查看:377
本文介绍了在Entity Framework Core中获取当前用户ID的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于如何获取当前登录用户的ID,ASP.NET Core的不同RC有很多不同的答案.我想在这里问一个明确的问题.请注意,project.json现在具有"Microsoft.AspNetCore.Identity.EntityFrameworkCore":"1.0.0"

There are a bunch of different answers floating around here for the different RC's of ASP.NET Core on how to get the ID of the currently logged in user. I wanted to ask the definite question here. Please note that project.json now has "Microsoft.AspNetCore.Identity.EntityFrameworkCore": "1.0.0"

使用RC1,您可以执行以下操作:

With RC1, you could do something like this:

using Microsoft.AspNet.Identity;
using System.Security.Claims;

User.GetUserId();

但是对于新发布的EF Core版本1,Microsoft.AspNet.Identity不是正确的版本.

But with the newly released version 1 of EF Core, Microsoft.AspNet.Identity is not the right version.

有人建议使用UserManager,这似乎是很多事情,只是为了获得当前登录的用户:

There was suggestions to use UserManager, which seems like a lot just to get the currently logged in user:

private Task<ApplicationUser> GetCurrentUserAsync() => _userManager.GetUserAsync(HttpContext.User);

var user = await GetCurrentUserAsync();
var userId = user?.Id;

我发现的另一种方法是:

Another method that I found was:

private readonly UserManager<ApplicationUser> _userManager;
_userManager.GetUserId(User)

因此,使用project.json中具有以下库的ASP.NET Core 1 RTM和EF Core 1,获取当前登录用户ID的正确方法是什么?

So with ASP.NET Core 1 RTM and EF Core 1 with the following libraries in project.json, what is the proper way to get the id of the currently logged in user?

"Microsoft.AspNetCore.Identity.EntityFrameworkCore": "1.0.0",
"Microsoft.AspNetCore.Mvc": "1.0.0",

推荐答案

ASP.NET Core Identity是通过DI在startup.cs中注入的-这样,您只需要通过构造函数注入Us​​erManager

ASP.NET Core Identity is injected via DI in the startup.cs - as such you just have to inject UserManager via a constructor

UserManager<ApplicationUser> userManager

然后您可以在方法中使用以下内容

You can then use the following in methods

_userManager.GetUserId(User);

当您使用个人用户帐户创建新的ASP.NET Core 1项目时,这就是在示例Web应用程序中使用的方式.

That's the way its used in the Sample Web Application when you create a new ASP.NET Core 1 project with Individual User Account.

这篇关于在Entity Framework Core中获取当前用户ID的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆