Pas*_* R. 4 asp.net-core blazor blazor-server-side
我HttpContext在 Blazor 服务器端视图中访问 以手动注销。我将此行添加到Startup.cs:services.AddHttpContextAccessor();并将其注入视图中@inject IHttpContextAccessor HttpContextAccessor。我有一个注销按钮,它尝试执行此代码:
await HttpContextAccessor.HttpContext.SignOutAsync("Cookies");
Run Code Online (Sandbox Code Playgroud)
但我收到以下错误消息:
System.InvalidOperationException: 'Headers are read-only, response has already started.'
Run Code Online (Sandbox Code Playgroud)
我怎样才能防止这个错误?
小智 11
如果您搭建了 Identity 并覆盖了通过模板创建项目时的旧“LogOut.cshtml”,则“注销”按钮将不会注销。假设您使用了默认的 IdentityUser 模型。我遇到了这个问题,如果其他人也遇到这个问题,我想添加这个问题。我正在使用 Blazor Server 和 .Net 5.0.3 的模板。您也可以删除 Logout.cshtml.cs 之后。
替换此 \Areas\Identity\Pages\Account\LogOut.cshtml
@page
@model LogoutModel
@{
ViewData["Title"] = "Log out";
}
<header>
<h1>@ViewData["Title"]</h1>
@{
if (User.Identity.IsAuthenticated)
{
<form class="form-inline" asp-area="Identity" asp-page="/Account/Logout" asp-route-returnUrl="@Url.Page("/", new { area = "" })" method="post">
<button type="submit" class="nav-link btn btn-link text-dark">Click here to Logout</button>
</form>
}
else
{
<p>You have successfully logged out of the application.</p>
}
}
</header>
Run Code Online (Sandbox Code Playgroud)
用。。。来代替
@page
@using Microsoft.AspNetCore.Identity
@attribute [IgnoreAntiforgeryToken]
@inject SignInManager<IdentityUser> SignInManager
@functions {
public async Task<IActionResult> OnPost()
{
if (SignInManager.IsSignedIn(User))
{
await SignInManager.SignOutAsync();
}
return Redirect("~/");
}
}
Run Code Online (Sandbox Code Playgroud)
这也让我感到困惑,但您需要在 Razor 页面(而不是 Blazor 组件)上提供注销功能。创建一个注销页面并将您的注销代码放入OnGetAsync()方法中。
然后您的注销按钮可以链接到注销页面。
不要使用IHttpContextAccessor.
我猜您正在使用ASP.NET Core Blazor 身份验证和授权新系统。如果没有,那么现在就开始吧。生命太短暂,不能浪费在其他事情上。这是迄今为止为 Blazor 身份验证和授权创建的最佳产品,并且它基于 Identity UI(当然这不是 Blazor)。此外,还有一些组件可以控制应用程序中的身份验证和授权流程,例如在布局中显示“登录”按钮和“注销”按钮,根据您的身份验证状态可互换地更改等。
请转到此页面并开始学习这个优秀的系统,然后来到这里解决您遇到的具体问题: https://learn.microsoft.com/en-us/aspnet/core/security/blazor/ ?view=aspnetcore- 3.0&tabs=视觉工作室
希望这可以帮助...
| 归档时间: |
|
| 查看次数: |
6886 次 |
| 最近记录: |