Blazored LocalStorage - 我做错了什么?

Blazored LocalStorage - what am i doing wrong?

我还在学习 blazor - 想添加一些非常简单流行的 Blazored LocalStorage 但有一些基本的麻烦/问题

代码是:

 using Microsoft.AspNetCore.Components.Authorization;
 using S3.Client.Shared.Services;
 using System.Security.Claims;

 namespace S3.Client.Helpers
  {
    public class MyAuthenticationStateProvider : AuthenticationStateProvider
    {
      private Blazored.LocalStorage.ISyncLocalStorageService l;
      public MyAuthenticationStateProvider(Blazored.LocalStorage.ISyncLocalStorageService l)
      {
        this.l= l;
      }

    public override async Task<AuthenticationState> GetAuthenticationStateAsync()
    {
        AuthenticationState aut;

        var claims = new List<Claim>
                {
                 new Claim(ClaimTypes.Name, "xxxyyyzzz"),
                 new Claim(ClaimTypes.Role, "Administrator")
                };

        ClaimsPrincipal p = new ClaimsPrincipal(new ClaimsIdentity(claims));
        l.SetItem<ClaimsPrincipal>("User", p);

        ClaimsPrincipal principal =  l.GetItem<ClaimsPrincipal>("User");


        bool x = p == principal;


        if (principal != null && principal.Claims.Count() >0 )
        {
            aut = new AuthenticationState(principal);
        }
        else
        {
            var anonymous = new ClaimsIdentity();
            aut = new AuthenticationState(new ClaimsPrincipal(anonymous));
        }
         return await Task.FromResult(aut);

请告诉我

为什么 x 是假的?它应该是同一个对象?

bool x = p.Claims.Count() == principal.Claims.Count() 

还是假的。 在调试中,我在 p._identities =1 a,d 中看到 principal._identities =0...

感谢和问候

这是 OP 在问题下方的评论中接受的答案:

serialization/deserialization 问题最可能的原因是用于 store/retrieve 数据的 JSON 序列化程序不喜欢 Principal 的结构(因此序列化程序以某种方式忽略了声明集合)。

解决方法是将声明提取到简单数据对象 (type/value) 并将声明集合存储为简单数组。