Blazor身份验证-用户在RazorHTML中可用,但不在@code中
创始人
2024-12-21 17:00:13
0

在Blazor应用程序的Razor页面中,@code部分是可以访问组件或页面相关数据逻辑的地方。但是,有时需要在razor HTML模板中访问一些数据,如用户身份验证状态等。在Blazor中可以通过注入“AuthenticationStateProvider”服务来实现这个需求。

以下是一个示例,演示如何在razor html模板中访问用户身份验证状态:

  1. 在程序的startup.cs文件中添加以下代码: services.AddAuthentication(); services.AddScoped();

2.创建StaticAuthenticationStateProvider.cs类,并实现“AuthenticationStateProvider”接口:

    public class StaticAuthenticationStateProvider : AuthenticationStateProvider
    {
        private readonly ClaimsIdentity _identity = new ClaimsIdentity(new[]
        {
            new Claim(ClaimTypes.Name, "TestUser"),
        }, "test");

        public override Task GetAuthenticationStateAsync()
        {
            var user = new ClaimsPrincipal(_identity);
            return Task.FromResult(new AuthenticationState(user));
        }
    }
  1. 在razor html模板中,通过调用“CascadingAuthenticationState”组件来访问用户身份验证状态:
    
        

User: @context.User.Identity.Name

这里使用了“CascadingAuthenticationState”组件,这个组件使用后,子组件都可以继承它的“AuthenticationState”对象,从而访问到用户身份验证状态。

通过上述步骤,就可以实现在razor HTML模板中访问用户身份验证状态的需求了。

相关内容

热门资讯

透视了解!aapoker发牌逻... 透视了解!aapoker发牌逻辑(透视)果然存在有挂(详细辅助攻略教程)辅助器中分为三种模型:软件透...
免费测试版!aapoker怎么... 免费测试版!aapoker怎么提高中牌率,hhpoker买挂,安装教程(有挂技巧);aapoker怎...
透视模拟器!德普之星透视辅助软... 透视模拟器!德普之星透视辅助软件激活码(透视)都是存在有挂(详细辅助AI教程)1、德普之星透视辅助软...
玩家必用!菠萝辅助器免费版的特... 玩家必用!菠萝辅助器免费版的特点,we poker辅助器下载,详细教程(有挂透视);致您一封信;亲爱...
透视存在!wepoker线上大... 透视存在!wepoker线上大神(透视)切实存在有挂(详细辅助安装教程)1、上手简单,内置详细流程视...
一分钟了解!wpk俱乐部辅助器... 一分钟了解!wpk俱乐部辅助器,拱趴大菠萝挂,线上教程(有挂方法);1.wpk俱乐部辅助器 ai辅助...
透视透视挂!如何下载德普之星辅... 透视透视挂!如何下载德普之星辅助软件(透视)确实是真的有挂(详细辅助扑克教程);1、下载好辅助软件之...
最新技巧!we-poker辅助... 最新技巧!we-poker辅助,hhpoker是真的还是假的,系统教程(有挂方法)1、玩家可以在hh...
透视辅助!xpoker辅助(透... 透视辅助!xpoker辅助(透视)原来真的是有挂(详细辅助解密教程);1、透视辅助简单,软件透明挂操...
总算了解!wepoker免费透... 总算了解!wepoker免费透视脚本,wepoker怎么开辅助,2025新版(有挂教程)1、很好的工...