如何根据用户是否登录来启用/禁用元素? [英] How to enable/disable elements depending whether the user is logged in or not?
问题描述
到目前为止,在所有示例中,我都看到了如何显示完全不同的视图的示例-一种用于用户登录时的情况,另一种用于用户未登录时的情况.
In all examples so far I saw examples how to show completely different views -- one for the case when the user is logged in, the other when the user is not logged in.
我想显示相同的元素,只是根据用户是否登录来启用/禁用某些元素.我虽然可以阅读 context.User.Identity.IsAuthenticated
并像这样使用它:
And I would like to display the same elements, just enable/disable some depending if the user is logged in or not. I though I can go with reading context.User.Identity.IsAuthenticated
and use it like this:
<NavLink class="nav-link" href="foobar"
IsDisabled="@(!(context.User.Identity?.IsAuthenticated ?? false))">
...
</NavLink>
但这需要 context
.此属性由 AuthorizeView
提供,并且此组件反过来在两组视图之间强制执行上述严格的划分.
But this requires context
. This property is provided by AuthorizeView
and this component in turn enforces the aforementioned strict split between two sets of views.
那么如何仅通过单个通用视图实现启用/禁用?
So how to achieve just enable/disable with single common view?
我完全知道这不是任何一种安全措施.
更新这两个答案都具有相同的效果(再次感谢您),但需要注意的是-仅在登录这两种方法后仍会返回未验证用户身份的信息.以下是后续问题:如何获取有关用户是否已登录的最新信息?
Update Both answers work with the same effect (thank you once again), but with small caveat -- just right after logging in both methods still returns info user is not authenticated. Here is the follow-up question: How to get fresh information whether the user is logged in?
推荐答案
您可以通过定义类型为 Task< AuthenticationState>
You can obtain the authentication state data by defining a cascading parameter of type Task<AuthenticationState>
这里是文档的完整示例:
Here's a full sample from the docs:
@page "/"
<button @onclick="LogUsername">Log username</button>
<p>@_authMessage</p>
@code {
[CascadingParameter]
private Task<AuthenticationState> authenticationStateTask { get; set; }
private string _authMessage;
private async Task LogUsername()
{
var authState = await authenticationStateTask;
var user = authState.User;
if (user.Identity.IsAuthenticated)
{
_authMessage = $"{user.Identity.Name} is authenticated.";
}
else
{
_authMessage = "The user is NOT authenticated.";
}
}
}
注意: CascadingAuthenticationState
组件是向感兴趣的方公开身份验证状态的组件...
Note: The CascadingAuthenticationState
component is the component that exposes the authentication state to interested parties...
这篇关于如何根据用户是否登录来启用/禁用元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!