11

我试图让 Asp.Net Identity 登录在 Visual Studio 模板应用程序中通过 Blazor 工作,它仍然使用 Razor Pages 和 MVC 登录,但只能让它在事件上工作OnInitAsync,这没有用,因为它需要通过单击按钮完成,而不是在页面加载时完成。

我的失败代码是

protected async Task LoginTest()
{
   await _SignInManager.SignInAsync(new ApplicationUser()
   { UserName = "test@test.com" }, true);
   UriHelper.NavigateTo("/", true);
}

我得到错误:

System.InvalidOperationException: The response headers cannot be modified because the response has already started.
at Microsoft.AspNetCore.HttpSys.Internal.HeaderCollection.ThrowIfReadOnly()
at Microsoft.AspNetCore.HttpSys.Internal.HeaderCollection.set_Item(String key, StringValues value)
at Microsoft.AspNetCore.Http.Internal.ResponseCookies.Append(String key, String value, CookieOptions options)
at Microsoft.AspNetCore.Authentication.Cookies.ChunkingCookieManager.AppendResponseCookie(HttpContext context, String key, String value, CookieOptions options)
at Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler.HandleSignInAsync(ClaimsPrincipal user, AuthenticationProperties properties)
at Microsoft.AspNetCore.Authentication.AuthenticationService.SignInAsync(HttpContext context, String scheme, ClaimsPrincipal principal, AuthenticationProperties properties)
at Microsoft.AspNetCore.Identity.SignInManager`1.SignInWithClaimsAsync(TUser user, AuthenticationProperties authenticationProperties, IEnumerable`1 additionalClaims)
at WebApplication3.Pages.Account.Login.RegUser() in C:\Users\david\source\repos\WebApplication3\WebApplication3\Pages\Account\Login.razor:line 28
at Microsoft.AspNetCore.Components.ComponentBase.CallStateHasChangedOnAsyncCompletion(Task task)
at Microsoft.AspNetCore.Components.Rendering.Renderer.GetErrorHandledTask(Task taskToHandle)

有没有人成功完成这项工作?正如我所提到的,如果我将上述函数放在方法中,我可以让它工作,OnInitAsync但在那里这样做并不好。

任何帮助将非常感激。

4

2 回答 2

2

在阅读大卫霍金斯的帖子和一些挖掘之后,我找到了一个解决方法,正如他在https://github.com/dotnet/aspnetcore/issues/13601#issuecomment-679870698上描述的那样。简单有效。

在建议的解决方案中,中间件中没有对用户/密码详细信息进行加密,因为它保留在服务器上。

截至目前(2021 年 4 月),ASP.Net Core 5 和 Identity 似乎不支持 Blazor 调用SignInManager*SignIn方法。到它被调用时,HTTP 标头已经被发送并且不能被修改/附加。

于 2021-04-14T23:50:17.117 回答
-2

我发现了这个相关的 GitHub 问题http://github.com/aspnet/AspNetCore/issues/11411

我最终使用 post-redirect-get 方法创建了一个变通解决方案。在帖子中,我使用用户详细信息加密了一个登录令牌,并将其作为 get 与查询字符串中的令牌一起传递到另一个页面,然后我读取了加密的令牌并登录了用户。

于 2019-07-10T22:12:26.607 回答