您无法在 Blazor Server App 中访问 HttpContext 对象,因为使用的协议是 SignalR,但始终为 HTTP 的初始请求除外,在这种情况下,您可以获取 HttpContext 对象(在 Blazor App 实例化之前) ,提取值,并将它们传递给您的 Blazor 应用程序。见this 回答怎么做...
但是,您可以将 AuthenticationStateProvider 服务注入到您的组件中,并访问声明的 ClaimsPrincipal(神奇地从 WindowsPrincipal 转换而来)对象,如下面的代码所示。
复制、运行和测试...
@page "/"
@using System.Security.Claims;
<div>@output</div>
@if (claims.Count() > 0)
{
<table class="table">
@foreach (var claim in claims)
{
<tr>
<td>@claim.Type</td>
<td>@claim.Value</td>
</tr>
}
</table>
}
@code{
private string output;
private IList<Claim> claims;
[Inject] AuthenticationStateProvider AuthenticationStateProvider { get; set; }
protected override async Task OnInitializedAsync()
{
var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
var user = authState.User;
if (user.Identity.IsAuthenticated)
{
output = $"{user.Identity.Name} is authenticated.";
claims = user.Claims.ToList();
}
else
{
output = "The user is not authenticated.";
}
}
}
更新:
实际上,有三种方法可以做到这一点。不推荐使用上面的第一个,因为 AuthenticationState 在被访问后永远不会更新。您需要刷新页面才能访问它的新实例。
第二种方法是将AuthenticationState的一个Task级联到你的组件中,等待Task,然后访问AuthenticationState。您可以这样做:
@page "/"
@code {
[CascadingParameter]
private Task<AuthenticationState> authenticationStateTask { get;
set; }
private string UserName {get; set;}
protected async override Task OnInitializedAsync()
{
// Await Task<AuthenticationState>
// and then retrieve the ClaimsPrincipal
var user = (await authenticationStateTask).User;
if (user.Identity.IsAuthenticated)
{
// Assign the user name to the
UserName = user.Identity.Name;
}
}
}
请注意,Task<AuthenticationState> 由 CascadingAuthenticationState 组件级联,位于 App 组件 (App.razor) 中。 CascadingAuthenticationState 组件
包含在新更改的 AuthenticationState 更改时向下流式传输的代码。
第三种方式是创建一个类服务如下:
public class UsertService
{
private readonly AuthenticationStateProvider authProvider;
public UserService (AuthenticationStateProvider authProvider)
{
this.authProvider = authProvider;
}
public async Task<string> GetUserName()
{
var authenticationStateTask = await
authProvider.GetAuthenticationStateAsync();
var user = authenticationStateTask.User;
if (user.Identity.IsAuthenticated)
{
// Executed only when the user is authenticated
return user.Identity.Name;
}
return "User not authenticated";
}
}
请注意,您可以扩展该类以提供其他值等。
现在您必须在 Startup 类中将此服务添加为 Scoped,如下所示:
public void ConfigureServices(IServiceCollection services)
{
// Code removed...
services.AddScoped<UserService>();
}
这就是您在组件中使用它的方式:
@page "/"
@inject UserService UserService
<div>Your user name: @name</div>
@code
{
private string name;
protected override async Task OnInitializedAsync()
{
name = await UserService.GetUserName();
}
}
注意:如果您需要更多帮助,可以通过我的电子邮件与我联系。在个人资料中查看...