c# - 如何从 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 "";
}
}
解决方案
如何从 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 或其他网络服务器技术。
推荐阅读
- sql - SQL Server 中的参照完整性
- microservices - 微服务与服务协同
- python - 区分大小写的实体识别
- reinforcement-learning - 对大卫·西尔弗第 2 讲中的奖励感到困惑
- outlook - 如何在 Outlook Web 加载项中更改电子邮件正文中特定单词的字体颜色?
- powershell - 如何在计算机列表上运行 Powershell
- sql - 如何连续写SQL语句不出错
- sass - 位于导入的 SASS 文件中的未定义变量
- python - 插入到表的 SQL db 适用于 1 项但不能使用多个
- powershell - Powershell Get -ChildItem:过滤 csv 文件和 -Recurse 不起作用