c# - 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 ...”我需要做什么?
解决方案
编辑:正如 Henk Holtermann 在评论中建议的那样,最好的方法是查看带有身份验证的官方 Blazor 模板(创建新项目 => Blazor 应用程序 => 创建 => 更改身份验证)。如果您出于某种原因必须使用 HttpContext,请使用我提供的链接中的示例:
HttpContext 不应在 Blazor 服务器端应用程序中使用,因为 SignalR 应用程序中通常没有可用的 HttpContext。
一种可能的解决方法是创建登录/注销剃须刀页面。Razor 页面可以访问 HttpContext,登录然后重定向到您的实际主页。您可以在此处找到详细说明。
推荐阅读
- c++ - 在构造函数中设置引用?
- excel - Excel中的时间跨度格式
- java - 如何使用 GSON 反序列化数据没有成员/参数名称的对象?
- php - 如何从 Android 应用程序连接 MySQL 数据库?
- javascript - 没有使用特定的先前键组合引发 keydown 事件
- php - PHP 在循环中使用查询的替代方法 5
- javascript - 如何在 ES 6 中将选择属性设置为单选按钮
- python - 编写函数来计算熊猫中的逐行元素的最佳方法是什么?
- docker - 在 docker 中创建网络是什么意思?
- javascript - 仅在页脚部分在最后一页的最底部打印表格页脚