我曾try 在.NET8中使用Blazor服务器进行自定义身份验证,但直到现在都没有成功.我是这个Blazor框架的新手,请判断一下我的工作流程,为什么我一直收到这个错误.我读了一些文章,但Blazor的事情发展得太快了,我try 了很多方法,但仍然没有成功.

我的页面树:

My page tree

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.

推荐答案

根据你的代码,我在我这边创建了一个测试演示,它工作得很好.因为你没有发布相关的代码来显示你对这件运动夹克的化妆.我会把我正在做的事情贴在我这边.

请注意:您应该确保login.razor是静态SSR.

更多详细信息,您可以参考以下代码:

@page "/login"
@using Microsoft.AspNetCore.Authentication
@using Microsoft.AspNetCore.Authentication.Cookies
@using System.Security.Claims
@inject NavigationManager NavManager

<h3>Login</h3>

<EditForm method="post" FormName="ClickLogin" OnSubmit="ClickLogin" Model="UserCredentials">
 
    <InputText @bind-Value="UserCredentials.Username" placeholder="Username"></InputText>
    <InputText @bind-Value="UserCredentials.Password" placeholder="Password" />

    <button type="submit" > SignIn</button>

</EditForm>


@code {
    [CascadingParameter]
    public HttpContext httpcontext { get; set; } = default!;

    [SupplyParameterFromForm]
    public Credential UserCredentials { get; set; } = new Credential();

    public async Task ClickLogin()
    {
        var claims = new List<Claim>();
        claims.Add(new Claim(ClaimTypes.Name, "test")); // 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("/");

    }
}

Prgram.cs:

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddRazorComponents()
    .AddInteractiveServerComponents();
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie(x =>
    {
        x.LoginPath = "/login";
    });
builder.Services.AddAuthorization();
builder.Services.AddCascadingAuthenticationState();
var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error", createScopeForErrors: true);
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();

app.UseAuthentication();
app.UseAuthorization();
app.UseAntiforgery();
app.UseStaticFiles();


app.MapRazorComponents<App>()
    .AddInteractiveServerRenderMode();

app.Run();

Csharp相关问答推荐

当MD5被废弃时,如何在Blazor WASM中使用它?

为什么使用DXGI输出复制和Direct 3D时捕获的图像数据全为零?

. NET 8使用COM向VB6公开

C#中使用BouncyCastle计算CMac

Razor视图Razor页面指向同一端点时的优先级

当前的文化决定了错误的文化

C#使用TextFieldParser读取.csv,但无法使用";0";替换创建的列表空条目

用于管理System.Text.Json中的多态反序列化的自定义TypeInfoResolver

在两个已具有一对多关系的表之间添加另一个一对多关系

Regex字母数字校验

使用System.Text.Json进行序列化时发生StackOverflow异常

如何在特定环境中运行dotnet测试?

我可以强制System.Text.Json.JsonSerializer以非递归方式工作吗?

在同一个捕获中可以有多种类型的异常吗?

我应该为C#12中的主构造函数参数创建私有属性吗?

为什么我可以在注册表编辑器中更改值,但不能在以管理员身份运行的C#表单应用程序中更改?

DropDownListFor未显示选定值

ASP.NET核心8:app.UseStaticFiles()管道执行顺序

根据优先级整理合同列表

如何在C#中抽象Vector256;T<;的逻辑以支持不同的硬件配置?