如何使用blazor创建cookie客户端

问题描述 投票:0回答:2

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

所以开始我已经成功注入了IHttpContextAccessor。现在,在我的Blazor功能中,我有:

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

在调试时,当我点击上面的代码行时,它出错:

“标题是只读的,响应已经开始。”

当然我不会在cookie中用“ddd”保存“test”,我只是想在此刻获得一个cookie来保存。

c# blazor
2个回答
2
投票

你将不得不使用JS互操作:

        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([Discussion] Microsoft.Interop.JSRuntime.Current has been removed)开始,Current属性不可用,因此请使用以下代码:

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

不要忘记在顶部注入IJSRuntime:

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

0
投票

您可以使用这样的服务器端方法来设置cookie:

    public async Task<IActionResult> OnPostAsync(string returnUrl = null)
    {
        returnUrl = returnUrl ?? Url.Content("~/");

        // *** !!! This is where you would validate the user !!! ***
        // In this example we just log the user in

        // (Always log the user in for this demo)
        var claims = new List<Claim>
            {
                new Claim(ClaimTypes.Name, Input.Email),
                new Claim(ClaimTypes.Role, "Administrator"),
            };

        var claimsIdentity = new ClaimsIdentity(
            claims, CookieAuthenticationDefaults.AuthenticationScheme);

        var authProperties = new AuthenticationProperties
        {
            IsPersistent = true,
            RedirectUri = this.Request.Host.Value
        };

        try
        {
            await HttpContext.SignInAsync(
            CookieAuthenticationDefaults.AuthenticationScheme,
            new ClaimsPrincipal(claimsIdentity),
            authProperties);

            return LocalRedirect(returnUrl);
        }
        catch 
        {
            return Page();
        }
    }

见:A Demonstration of Simple Server-side Blazor Cookie Authentication

© www.soinside.com 2019 - 2024. All rights reserved.