我無法在 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"); } }}我收到異?!盁o法修改響應標頭,因為響應已經開始?!?在代碼“await _httpContextAccessor.HttpContext.SignInAsync...”上我需要做什么?
1 回答

揚帆大魚
TA貢獻1799條經驗 獲得超9個贊
編輯:正如 Henk Holtermann 在評論中建議的那樣,最好的方法是查看帶有身份驗證的官方 Blazor 模板(創建新項目 => Blazor 應用程序 => 創建 => 更改身份驗證)。如果您出于某種原因必須使用 HttpContext,請使用我提供的鏈接中的示例:
HttpContext 不應在 Blazor 服務器端應用程序中使用,因為 SignalR 應用程序中通常沒有可用的 HttpContext。
一種可能的解決方法是創建登錄/注銷剃刀頁面。razor 頁面可以訪問 HttpContext、登錄然后重定向到您的實際主頁。
- 1 回答
- 0 關注
- 316 瀏覽
添加回答
舉報
0/150
提交
取消