亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Blazor -> 頁面登錄 -> 無法執行 _httpContextAccessor.

Blazor -> 頁面登錄 -> 無法執行 _httpContextAccessor.

PHP
萬千封印 2024-01-20 21:40:57
我無法在 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、登錄然后重定向到您的實際主頁。


查看完整回答
反對 回復 2024-01-20
  • 1 回答
  • 0 關注
  • 316 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號