首页 > 解决方案 > Blazor -> 页面登录 -> 无法执行 _httpContextAccessor.HttpContext.SignInAsync()

问题描述

我无法在 Blazor(服务器端)上为登录用户(cookie 身份验证)创建功能例如创建一些代码:

@using Microsoft.AspNetCore.Http;
@using Microsoft.AspNetCore.Authentication;
@using Microsoft.AspNetCore.Authentication.Cookies;
@using System.Security.Claims;
@inject IHttpContextAccessor _httpContextAccessor
@inject NavigationManager UriHelper


<form class="form-group">
    <input class="form-control" @bind="Name" type="text" />
    <input class="form-control" @bind="Password" type="password" />
    <button type="button" @onclick="@(()=>SbmForm())" class="btn btn-light">Sbm</button>   
</form>


@code{
    [Parameter]
    public string Name { get; set; }
    public string Password { get; set; }  

    public async Task SbmForm()
    {
        if (!String.IsNullOrEmpty(Name))
        {
            var claims = new[] { new Claim(ClaimTypes.Name, Name),
                new Claim(ClaimTypes.Role, "Admin") };

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

            try
            {
                await _httpContextAccessor.HttpContext.SignInAsync(
                  CookieAuthenticationDefaults.AuthenticationScheme,
                  new ClaimsPrincipal(identity),
                  new AuthenticationProperties
                  {
                      IsPersistent = true
                  });
            }
            catch(Exception e)
            {
                Console.WriteLine(e.Message);
            }
            UriHelper.NavigateTo("/counter");
        }
    }
}

我收到异常“无法修改响应标头,因为响应已经开始。” 关于代码“等待_httpContextAccessor.HttpContext.SignInAsync ...”我需要做什么?

标签: c#.netasp.net-coreblazorblazor-server-side

解决方案


编辑:正如 Henk Holtermann 在评论中建议的那样,最好的方法是查看带有身份验证的官方 Blazor 模板(创建新项目 => Blazor 应用程序 => 创建 => 更改身份验证)。如果您出于某种原因必须使用 HttpContext,请使用我提供的链接中的示例:

HttpContext 不应在 Blazor 服务器端应用程序中使用,因为 SignalR 应用程序中通常没有可用的 HttpContext。

一种可能的解决方法是创建登录/注销剃须刀页面。Razor 页面可以访问 HttpContext,登录然后重定向到您的实际主页。您可以在此处找到详细说明。


推荐阅读