gpt4 book ai didi

cookies - 在 Blazor 服务器端创建和读取 Cookie

转载 作者:行者123 更新时间:2023-12-04 00:54:40 30 4
gpt4 key购买 nike

在 Blazor 服务器端创建和读取 cookie 的最简单方法是什么。
似乎所有解决方案都适用于 Blazor Web 程序集,每当我使用这些解决方案时, Response.Cookies.Append("") 和 Request.Cookies[] 选项都不起作用。

最佳答案

wwwroot/index.html (Blazor WebAssembly) 或 Pages/_Host.cshtml (Blazor Server) 中,编写以下 javascript 代码:

  <script>
window.WriteCookie = {

WriteCookie: function (name, value, days) {

var expires;
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toGMTString();
}
else {
expires = "";
}
document.cookie = name + "=" + value + expires + "; path=/";
}
}
window.ReadCookie = {
ReadCookie: function (cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
}
</script>
然后,将以下示例代码写入 Razor 组件 (.razor):
@inject IJSRuntime JsRuntime;
<button class="btn" @onclick="WriteCookies">
Write Cookie
</button>
<button class="btn" @onclick="ReadCookies">
Read Cookie
</button>

<p>The cookie is @myCookieValue</p>
@code {
public string myCookieValue { get; set; } = "";
protected async Task WriteCookies()
{

await JsRuntime.InvokeAsync<object>("WriteCookie.WriteCookie", "cookieName", "cookieValue", DateTime.Now.AddMinutes(1));

}
protected async Task ReadCookies()
{

myCookieValue= await JsRuntime.InvokeAsync<string>("ReadCookie.ReadCookie", "cookieName");

}

}

关于cookies - 在 Blazor 服务器端创建和读取 Cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63478620/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com