我无法在 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");
}
}
}
我收到异常“无法修改响应标头,因为响应已经开始。” 在代码“await _httpContextAccessor.HttpContext.SignInAsync...”上我需要做什么?
扬帆大鱼