.net - 使用 HttpContextAccessor 访问 dotnet 3.1 中的登录用户
问题描述
好的,所以我在这里变得不耐烦了。:) 我试图通过访问 IHttpContextAccessor 通过 HttpContext.User 访问我的登录用户,但没有用户可用,也没有任何声明。这里使用的是 Dotnet core 3.1。这基本上是我的理解:使用 HttpContext.SignInAsync(...看到 cookie 正确附加到请求但没有完成一些转换。有谁知道我错过了什么?
//My controller action:
var claimsIdentity = new ClaimsIdentity("Application");
claimsIdentity.AddClaim(emailClaim);
... more claims
await HttpContext.SignInAsync(
"Application",
new ClaimsPrincipal(claimsIdentity)
);
// Startup.cs:ConfigureServices
services.AddHttpContextAccessor();
// In a MyClass
MyClass(IHttpContextAccessor accessor)
{
accessor.HttpContext.Claims; // Nothing
}
解决方案
据我所知,如果我们使用了 cookie 身份验证并且用户已经登录,我们可以从 httpcontext 访问器获取声明。
我建议您可以首先确保浏览器已通过 cookie 将身份验证令牌设置为服务器。
然后我建议您可以确保将 myclass 注入为作用域而不是 Singleton。
更多细节,您可以参考下面的测试代码来读取cookie。
我的课:
public class Myclass
{
public IHttpContextAccessor _accessor { get; set; }
public Myclass(IHttpContextAccessor accessor)
{
_accessor = accessor;
var re = accessor.HttpContext.User.Identity as ClaimsIdentity;
int i = 0;
}
public string GetName() {
var re = _accessor.HttpContext.User.Identity as ClaimsIdentity;
string name = re.Claims.First(x => x.Type == "name").Value;
return name;
}
}
启动.cs:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie();
services.AddHttpContextAccessor();
services.AddScoped(typeof(Myclass));
}
用法:
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
public Myclass test { get; set; }
public HomeController(ILogger<HomeController> logger, Myclass _test)
{
_logger = logger;
test = _test;
}
public async Task<IActionResult> IndexAsync()
{
var claimsIdentity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme);
claimsIdentity.AddClaim(new Claim("name", "aaaa"));
await HttpContext.SignInAsync(
CookieAuthenticationDefaults.AuthenticationScheme,
new ClaimsPrincipal(claimsIdentity)
);
return View();
}
public async Task<IActionResult> PrivacyAsync()
{
var re= test.GetName();
return View();
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
结果:
推荐阅读
- javascript - 使用 Python 和 Flask。我正在尝试使用 javascript 让我的 flash 消息在几秒钟后消失
- javascript - 将上下文传递给回调中的 ajax 调用
- c++ - 如何在命名空间内创建一个类?
- r - 通过 grImport2 绘制 svg 在终端中可以正常工作,而不是通过 knitr
- c++11 - 通过值捕获本地指针,其余的在 lambda 中通过引用捕获
- javascript - 为什么我的 jqRouter.renderViewSuccess 事件处理程序被调用了两次?
- excel - 根据单元格值隐藏或取消隐藏工作表
- android - Android recyclerview defauilitemanimator 更改持续时间
- dropbox - 将 Google 照片或 DropBox 中的图像列表导出为 CSV
- reactjs - React Navigation V2 不显示栏,React Native