在 Blazor 组件中获取当前用户 [英] Get Current User in a Blazor component
问题描述
我正在使用 Blazor 和 Windows 身份验证启动一个新站点,并且需要识别查看页面/组件的当前用户.
I'm starting a new site with Blazor and Windows Authentication and need to identify the current user viewing the page/component.
对于 Razor 页面,可以使用 Context.User.Identity.Name
访问当前用户名,但这似乎不适用于 Blazor 组件.我尝试将 HttpContext 注入到组件中,但 Context 在运行时为 null.
For a Razor Page, the current user name can be accessed with Context.User.Identity.Name
, but that doesn't seem to work in a Blazor component. I've tried injecting HttpContext into the component but the Context is null at runtime.
作为奖励,我最终希望将其合并到 Startup.cs 中,因此我只需要获取一次用户名,就可以为我的应用程序利用企业用户类(使用 EF Core).也将不胜感激针对该用例量身定制的答案.
As a bonus, I will eventually want to incorporate this into Startup.cs so I only need to get the username once and can leverage a corporate user class (with EF Core) for my applications. Answers tailored to that use case would also be appreciated.
推荐答案
在组件中获取用户的三种可能性(一个页面就是一个组件):
There are three possibilities for getting the user in a component (a page is a component):
- 注入
IHttpContextAccessor
并从中访问HttpContext
,然后User
;需要在Startup.ConfigureServices
中注册IHttpContextAccessor
,一般使用AddHttpContextAccessor
- 注入一个
AuthenticationStateProvider
属性,调用GetAuthenticationStateAsync
并从中获取User
- 将您的组件包装在
组件中,声明一个Task
属性并调用它以获取User
(类似于#2)
- Inject
IHttpContextAccessor
and from it accessHttpContext
and thenUser
; need to registerIHttpContextAccessor
inStartup.ConfigureServices
, normally usingAddHttpContextAccessor
- Inject a
AuthenticationStateProvider
property, callGetAuthenticationStateAsync
and getUser
from it - Wrap your component in a
<CascadingAuthenticationState>
component, declare aTask<AuthenticationState>
property and call it to get theUser
(similar to #2)
在此处查看更多信息:https://docs.microsoft.com/en-us/aspnet/core/security/blazor.
See more here: https://docs.microsoft.com/en-us/aspnet/core/security/blazor.
这篇关于在 Blazor 组件中获取当前用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!