简体   繁体   English

Blazor ProtectedSessionStorage 对象 NULL

[英]Blazor ProtectedSessionStorage object NULL

I've made a helper class on ProtectedSessionStorage to Read/Write data我在 ProtectedSessionStorage 上做了一个辅助类来读/写数据

using Microsoft.AspNetCore.ProtectedBrowserStorage;
public class SessionObjectHelper
{
    [Inject] private ProtectedSessionStorage ProtectedSessionStore { get; set; }
    
    public async Task<string> GetTestProperty()
    {
        var value = await ProtectedSessionStore.GetAsync<string>("TestProperty") ?? string.Empty;

        return value;
    }
    
    public async Task SetTestProperty(string value)
    {
        await ProtectedSessionStore.SetAsync("TestProperty", value);
    }       
}

If I call any of these methods from a Component as illustrated below, ProtectedSessionStore is always NULL如果我从组件调用这些方法中的任何一个,如下所示,ProtectedSessionStore 始终为 NULL

[Inject] private SessionObjectHelper SessionObjectHelper { get; set; }

protected override async Task OnInitializedAsync()
{
    var testProperty= await SessionObjectHelper.GetTestProperty();
}

Your SessionObjectHelper class should declare a constructor to get the injected service, not use the [Inject] attribute, eg您的SessionObjectHelper类应该声明一个构造函数来获取注入的服务,而不是使用[Inject]属性,例如

    public class SessionObjectHelper
    {
        private ProtectedSessionStorage storage;

        public SessionObjectHelper(ProtectedSessionStorage storage)
        {
                this.storage = storage;
        }

The [Inject] attribute is designed to work with Razor Components, not regular classes. [Inject]属性旨在与 Razor 组件一起使用,而不是常规类。

You can then use然后你可以使用

[Inject] public SessionObjectHelper SessionObjectHelper { get; set; }

In your component.在您的组件中。 Note I changed to public - if it's private the runtime won't be able to see/set it.注意我更改为public - 如果它是私有的,运行时将无法看到/设置它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM