gpt4 book ai didi

c# - 通知所有组件 Blazor 中的身份验证已更改

转载 作者:行者123 更新时间:2023-12-05 06:57:42 26 4
gpt4 key购买 nike

我有一个带有大量 html 标记的 Blazor(版本 net5.0)组件,这里是它的一部分:

<a class="@(IsAuthenticated?"":"hide")" href="#">My link for logged in users</a>

这是我的 C# 代码 (MyComponent.Razor):

    [CascadingParameter] private Task<AuthenticationState> authenticationState { get; set; }
private AuthenticationState auth;
public bool IsAuthenticated { get; set; }

protected async override Task OnInitializedAsync()
{
auth = await authenticationState;
var user = auth.User.Identity.IsAuthenticated;
await base.OnInitializedAsync();
}

成功登录后,在我的登录组件中调用StateHasChanged();

  void Login()
{
...
StateHasChanged();
}

但是在登录后,除非我刷新页面以便组件重新呈现自己,否则不会应用对 MyComponent 的任何更改。

注意:我不想使用 AuthorizeView,因为正如我提到的,MyComponent 中有很多标记和组件,我不想为每个我想根据用户身份验证更改其行为的样式或元素设置一个 AuthorizeView

更新:我的 App.razor 组件中有以下代码:

<Router AppAssembly="@typeof(Program).Assembly">
<Found Context="routeData">
<AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(Layout)" >
<Authorizing>
<text> my Custom Authotizing in app.razor ...</text>
</Authorizing>
<NotAuthorized>
<text> my Custom NOT Authotized in app.razor ...</text>
</NotAuthorized>
</AuthorizeRouteView>
</Found>
<NotFound>
<CascadingAuthenticationState>
<LayoutView Layout="@typeof(Layout)">
<p>Sorry, there's nothing at this address.</p>
</LayoutView>
</CascadingAuthenticationState>
</NotFound>
</Router>

最佳答案

查看 AuthorizedView 源代码,我终于明白我应该使用 OnParametersSetAsync 和一个属性:

<a class="@MyClassProp" href="#">My link for logged in users</a>

代码:

public string MyClassProp { get; set; } = "hide";
public async Task<string> GetClassAsync()=> (await authenticationState).User.Identity.IsAuthenticated ? "" : "hide";

protected async override Task OnParametersSetAsync()
{
MyClassProp = await GetClassAsync(); // also call GetClass in OnInitializedAsync
StateHasChanged();
await base.OnParametersSetAsync();
}

我在问题中创建的 IsAuthenticated 属性始终等于其初始状态,并且不会随 AuthenticationState 更改而改变,即使我在OnParametersSetAsync。不必在登录和注销方法中调用 StateHasChanged()。如果我不使用 MyClassProp 属性,而是从标记中调用 GetClassAsync,它也不起作用。

警告: 通过为未经授权的用户设置 css 类来隐藏元素的整个方法存在安全问题,因为内容仍然可以被用户公开或修改只需使用他们的浏览器即可。

关于c# - 通知所有组件 Blazor 中的身份验证已更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64859224/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com