如何使用 Blazor 保存设置到客户端?
话不多说,直接上代码
- 添加服务类, 完整代码比较长,放到文章最后
public interface ICookie
{
public Task RemoveValue(string key);
public Task SetValue(string key, string value, int? days = null);
public Task<string> GetValue(string key, string def = "");
}
public interface IStorage
{
public Task RemoveValue(string key);
public Task SetValue<TValue>(string key, TValue value) where TValue : class;
public Task<TValue?> GetValue<TValue>(string key, TValue? def = null) where TValue : class;
}
- 然后在 startup.cs 中添加此服务
services.AddScoped<IStorage, StorageService>();
services.AddScoped<ICookie, CookieService>();
- 页面使用
[Inject, NotNull] protected IStorage? Storage { get; set; }
[Inject, NotNull] protected ICookie? Cookie { get; set; }
string Username;
Username = await Storage.GetValue<string>("username");
await Storage.SetValue("username", States.Username);
await Storage.RemoveValue("username");
Username = await Storage.GetValue("username");
await Cookie.SetValue("username", States.Username);
await Cookie.RemoveValue("username");
- 服务类代码
LocalStorage
using Microsoft.JSInterop;
public interface IStorage
{
public Task RemoveValue(string key);
public Task SetValue<TValue>(string key, TValue value) where TValue : class;
public Task<TValue?> GetValue<TValue>(string key, TValue? def = null) where TValue : class;
}
public class StorageService : IStorage
{
readonly IJSRuntime JSRuntime;
public StorageService(IJSRuntime jsRuntime)
{
JSRuntime = jsRuntime;
}
public async Task SetValue<TValue>(string key, TValue value) where TValue : class
{
await JSRuntime.InvokeVoidAsync("eval", $"localStorage.setItem('{key}', '{value}')");
}
public async Task<TValue?> GetValue<TValue>(string key, TValue? def) where TValue : class
{
var cValue = await JSRuntime.InvokeAsync<TValue>("eval", $"localStorage.getItem('{key}');");
return cValue??def;
}
public async Task RemoveValue(string key)
{
await JSRuntime.InvokeVoidAsync("eval", $"localStorage.removeItem('{key}')");
}
}
Cookie
using Microsoft.JSInterop;
public interface ICookie
{
public Task RemoveValue(string key);
public Task SetValue(string key, string value, int? days = null);
public Task<string> GetValue(string key, string def = "");
}
public class CookieService : ICookie
{
readonly IJSRuntime JSRuntime;
string expires = "";
public CookieService(IJSRuntime jsRuntime)
{
JSRuntime = jsRuntime;
ExpireDays = 300;
}
public async Task SetValue(string key, string value, int? days = null)
{
var curExp = (days != null) ? (days > 0 ? DateToUTC(days.Value) : "") : expires;
await SetCookie($"{key}={value}; expires={curExp}; path=/");
}
public async Task<string> GetValue(string key, string def = "")
{
var cValue = await GetCookie();
if (string.IsNullOrEmpty(cValue)) return def;
var vals = cValue.Split(';');
foreach (var val in vals)
if (!string.IsNullOrEmpty(val) && val.IndexOf('=') > 0)
if (val.Substring(0, val.IndexOf('=')).Trim().Equals(key, StringComparison.OrdinalIgnoreCase))
return val.Substring(val.IndexOf('=') + 1);
return def;
}
public async Task RemoveValue(string key)
{
await SetCookie($"{key}=; expires=Thu, 01 Jan 1970 00:00:01 GMT; path=/");
}
private async Task SetCookie(string value)
{
await JSRuntime.InvokeVoidAsync("eval", $"document.cookie = \"{value}\"");
}
private async Task<string> GetCookie()
{
return await JSRuntime.InvokeAsync<string>("eval", $"document.cookie");
}
public int ExpireDays
{
set => expires = DateToUTC(value);
}
private static string DateToUTC(int days) => DateTime.Now.AddDays(days).ToUniversalTime().ToString("R");
}
好了, 你学会了吗?
关联项目
FreeSql QQ群:4336577
BA & Blazor QQ群:795206915
Maui Blazor 中文社区 QQ群:645660665
知识共享许可协议
本作品采用 知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议 进行许可。欢迎转载、使用、重新发布,但务必保留文章署名AlexChow(包含链接: https://github.com/densen2014 ),不得用于商业目的,基于本文修改后的作品务必以相同的许可发布。如有任何疑问,请与我联系 。
转载声明
本文来自博客园,作者:周创琳 AlexChow,转载请注明原文链接:https://www.cnblogs.com/densen2014/p/17467435.html
AlexChow
今日头条 | 博客园 | 知乎 | Gitee | GitHub
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· 清华大学推出第四讲使用 DeepSeek + DeepResearch 让科研像聊天一样简单!
· 实操Deepseek接入个人知识库
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· 易语言 —— 开山篇