如何使用blazor创建Cookie客户端 [英] How do I create a cookie client side using blazor

查看:428
本文介绍了如何使用blazor创建Cookie客户端的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个进入服务器的登录页面,该页面获取一堆数据,然后我想获取其中的一些数据,并使用客户端上的Blazor将其保存到cookie中.

I have a login page that goes off to the server gets a bunch of data, then I want to take some of that data and save it into a cookie using Blazor on the client.

因此,要开始,我已经成功注入了IHttpContextAccessor.现在,在我的Blazor功能中,我有:

So To start I have successfully injected IHttpContextAccessor. and for now in my Blazor function I have:

httpContextAccessor.HttpContext.Response.Cookies.Append("test", "ddd");

在调试中,当我碰到上面的代码时,它的错误是:

in debug when I hit the above line of code it errors with:

标头是只读的,响应已经开始."

"Headers are read-only, response has already started."

当然,我不会在cookie中保存"test"和"ddd",我只是想立即保存一个cookie.

Of course I will not be saving "test" with "ddd" in the cookie, I'm just trying to get a cookie to save at the moment.

推荐答案

您将必须使用JS interop:

You will have to use JS interop:

        public async static Task WriteCookieAsync(string name, string value, int days)
        {
           var test = await JSRuntime.Current.InvokeAsync<object>("blazorExtensions.WriteCookie", name, value, days);
        }

从ASP.NET Core 3.0.0-preview3开始( [讨论] Microsoft.Interop.JSRuntime .Current已被删除),Current属性不可用,因此请使用以下代码:

Starting with ASP.NET Core 3.0.0-preview3 ([Discussion] Microsoft.Interop.JSRuntime.Current has been removed), the Current property is not available, so use the following code:

var test = await JSRuntime.InvokeAsync<string>("blazorExtensions.WriteCookie", name, value, days);

别忘了在顶部插入IJSRuntime:

Don't forget to inject IJSRuntime at the top:

@inject IJSRuntime JSRuntime

还有这个JS:

window.blazorExtensions = {

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=/";
}
}

这篇关于如何使用blazor创建Cookie客户端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆