首页 > 解决方案 > 如何从 blazor 中的 .cs 文件访问浏览器本地存储?

问题描述

首先,我可以访问 .razor 页面中的本地存储数据。我的意思是我无法访问 .cs 文件中的本地存储数据。我怎样才能访问?

_Imports.razor:

@using Microsoft.AspNetCore.Components.Server.ProtectedBrowserStorage;
@inject ProtectedLocalStorage protectedLocalStorage

任何人 .razor 文件:

await protectedLocalStorage.SetAsync(key, JsonSerializer.Serialize(instance));

上面的代码对我有用,但我想另外从 .cs 文件中调用 protectedLocalStorage 。

PS抱歉语法错误

编辑:我在 startup.cs 中使用 IHttpClientFactory 并且我想在 api 请求之前添加令牌作为标头。

启动.cs

    services.AddHttpClient("api", hc =>
    {
        hc.BaseAddress = new Uri("http://localhost:5000/");

        string tokenVal = tokenService.GetToken();

        if (!String.IsNullOrEmpty(tokenVal))
            hc.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", tokenVal);
    });

我想从此 .cs 文件中从本地存储中获取令牌值

public class TokenService : ITokenService
{
    private IHttpContextAccessor httpContextAccessor;

    public TokenService(IHttpContextAccessor HttpContextAccessor, IProtected) => httpContextAccessor = HttpContextAccessor;

    public string GetToken()
    {
        return "";
    }
}

标签: c#browserlocal-storageblazorblazor-server-side

解决方案


如何从 blazor 中的 .cs 文件访问浏览器本地存储?

ASP.NET 在大多数构造函数中都支持注入。扩展OP的例子:

// Startup.cs -> ConfigureServices(IServiceCollection services)
    // Probably not necessary in your case but, to be thorough:
    services.AddScoped<ProtectedLocalStorage>();

// SomeFile.cs
public class TokenService : ITokenService
{
    // Ignore for the moment that these are being used in the same context
    private IHttpContextAccessor httpContextAccessor;
    private readonly ProtectedBrowserStorage _storage;

    // Injection can happen here in ASP.NET
    public TokenService(
        IHttpContextAccessor HttpContextAccessor, 
        ProtectedBrowserStorage storage) 
    {
        httpContextAccessor = HttpContextAccessor;
        // injection works but the PBS service might not: see below
        _storage = storage;
    }

    //..
}

但是,我不推荐这个ProtectedBrowserStorage,因为它IJSRuntime在引擎盖下使用。如果您尝试在不支持 javascript 的上下文中使用它(例如Startup.Configure,在客户端仍在等待响应并且无法执行 javascript 的情况下),您将遇到错误。在 Blazor 中,ProtectedBrowserStorage只能从 Blazor 组件直接或间接调用;为了简单起见,请将其包装在仅与组件一起使用的类中,或者将其保留在组件本身中。

因此,如果您尝试这样做:

我在 startup.cs 中使用 IHttpClientFactory 并且我想在 api 请求之前添加令牌作为标头。

ProtectedBrowserStorage不是适合您工具。使用 cookie 或其他网络服务器技术。


推荐阅读