如何使用blazor创建Cookie客户端

时间:2019-01-03 14:50:32

标签: c# blazor

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

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

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

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

  

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

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

4 个答案:

答案 0 :(得分:2)

您将不得不使用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([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=/";
}
}

答案 1 :(得分: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

答案 2 :(得分:0)

您可以在void OnSceneLoaded(Scene scene, LoadSceneMode mode) 标记内添加由@Flores in _ javaScript解释的Host.cshtml

<script>

答案 3 :(得分:0)

如果要避免外部脚本依赖性

await jsRuntime.InvokeVoidAsync("eval", $"document.cookie = \"{cookieValue}\"")

保留属性以转义cookie值。