在 Blazor 组件中获取当前用户 [英] Get Current User in a Blazor component

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

问题描述

我正在使用 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):

  1. 注入IHttpContextAccessor并从中访问HttpContext,然后User;需要在Startup.ConfigureServices中注册IHttpContextAccessor,一般使用AddHttpContextAccessor
  2. 注入一个 AuthenticationStateProvider 属性,调用 GetAuthenticationStateAsync 并从中获取 User
  3. 将您的组件包装在 组件中,声明一个 Task 属性并调用它以获取 User (类似于#2)
  1. Inject IHttpContextAccessor and from it access HttpContext and then User; need to register IHttpContextAccessor in Startup.ConfigureServices, normally using AddHttpContextAccessor
  2. Inject a AuthenticationStateProvider property, call GetAuthenticationStateAsync and get User from it
  3. Wrap your component in a <CascadingAuthenticationState> component, declare a Task<AuthenticationState> property and call it to get the User (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屋!

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