我曾try 在.NET8中使用Blazor服务器进行自定义身份验证,但直到现在都没有成功.我是这个Blazor框架的新手,请判断一下我的工作流程,为什么我一直收到这个错误.我读了一些文章,但Blazor的事情发展得太快了,我try 了很多方法,但仍然没有成功.
我的页面树:
Program.cs
个
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(x =>
{
x.LoginPath = "/login";
});
builder.Services.AddAuthorization();
builder.Services.AddCascadingAuthenticationState();
///////////////////////////
app.UseAuthentication();
app.UseAuthorization();
Login.razor
个
@using Microsoft.AspNetCore.Authentication
@using Microsoft.AspNetCore.Authentication.Cookies
@using System.Security.Claims
@* some razor component *@
@code{
[CascadingParameter]
public HttpContext httpcontext { get; set; } = default!;
public async Task ClickLogin()
{
_loginbtnLoading = true;
if (!string.IsNullOrEmpty(_ntid) && !string.IsNullOrEmpty(_password))
{
await Task.Delay(2000);
//I'm using LDAP for checking user signin
var loginOK = ILoginServices.CheckLoginStatus(_ntid, _password);
if (loginOK.success)
{
var claims = new List<Claim>();
claims.Add(new Claim(ClaimTypes.Name, _ntid)); // add more claims
var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
var principal = new ClaimsPrincipal(claimsIdentity);
// Sign in the user
await httpcontext.SignInAsync(principal);
NavManager.NavigateTo("/home");
}
else
{
Snackbar.Add(loginOK.errorMessage, Severity.Error);
}
}
else
{
Snackbar.Add("Please key in all the required info", Severity.Error);
}
_loginbtnLoading = false;
}
}
产生的错误是
System.InvalidOperationException: Headers are read-only, response has already started.
个