Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-core/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在服务器端Blazor下使用SignInManager.SignInAsync(……)时,它会引发异常_C#_Asp.net Core_Blazor Server Side - Fatal编程技术网

C# 在服务器端Blazor下使用SignInManager.SignInAsync(……)时,它会引发异常

C# 在服务器端Blazor下使用SignInManager.SignInAsync(……)时,它会引发异常,c#,asp.net-core,blazor-server-side,C#,Asp.net Core,Blazor Server Side,我正在学习服务器端blazor并尝试学习身份验证。无论何时使用SignInManager.SignInAsync(……),它都会引发以下异常: System.InvalidOperationException:无法删除响应头 已修改,因为响应已启动。 Microsoft.AspNetCore.HttpSys.Internal.HeaderCollection.ThrowIfReadOnly() 在 Microsoft.AspNetCore.HttpSys.Internal.HeaderColle

我正在学习服务器端blazor并尝试学习身份验证。无论何时使用SignInManager.SignInAsync(……),它都会引发以下异常:

System.InvalidOperationException:无法删除响应头 已修改,因为响应已启动。 Microsoft.AspNetCore.HttpSys.Internal.HeaderCollection.ThrowIfReadOnly() 在 Microsoft.AspNetCore.HttpSys.Internal.HeaderCollection.set\u项(字符串 键,StringValues(值)位于 Microsoft.AspNetCore.Http.ResponseCookies.Append(字符串键,字符串 值,CookieOptions(选项) Microsoft.AspNetCore.Authentication.Cookies.ChunkingCookieManager.AppendResponseCookie(HttpContext 上下文、字符串键、字符串值、CookieOptions) Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler.HandleSignInAsync(ClaimsPrincipal) 用户,AuthenticationProperties)位于 Microsoft.AspNetCore.Authentication.AuthenticationService.SignInAsync(HttpContext 上下文、字符串方案、ClaimsPrincipal主体、, AuthenticationProperties) Microsoft.AspNetCore.Identity.SignInManager
1.SignInWithClaimsAsync(TUser
用户,AuthenticationProperties AuthenticationProperties,IEnumerable
1 GroupMembersInfo.Pages.RegisterUser.Register()上的附加声明) 在里面 C:\my_work\Blazor_learning\GroupMembersInfo\Pages\RegisterUser.razor:line 52在 Microsoft.AspNetCore.Components.ComponentBase.CallStateHasChangedOnAsyncCompletion(任务 任务)在 Microsoft.AspNetCore.Components.Forms.EditForm.HandleSubmitAsync()
在 Microsoft.AspNetCore.Components.ComponentBase.CallStateHasChangedOnAsyncCompletion(任务 任务)在 Microsoft.AspNetCore.Components.RenderTree.Renderer.GetErrorHandledTask(任务 taskToHandle)

我认为异常是从我突出显示的方法中抛出的。那么我该如何缓解这个问题呢。这是我的密码

starup.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Components;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using GroupMembersInfo.Data;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.Components.Server;

namespace GroupMembersInfo
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContextPool<AppDbContext>(
                options => options.UseSqlServer(Configuration.GetConnectionString("GMIDbConnection")));

            services.AddIdentity<IdentityUser, IdentityRole>(options => options.SignIn.RequireConfirmedAccount = true)
                .AddEntityFrameworkStores<AppDbContext>();

            services.AddRazorPages();
            services.AddServerSideBlazor();
            services.AddScoped<AuthenticationStateProvider, RevalidatingIdentityAuthenticationStateProvider<IdentityUser>>();
            services.AddSingleton<WeatherForecastService>();

            services.ConfigureApplicationCookie(options =>
            {
                options.SlidingExpiration = true;

                options.Events.OnRedirectToLogin = cxt =>
                {
                    cxt.Response.StatusCode = 401;
                    return Task.CompletedTask;
                };

                options.Events.OnRedirectToAccessDenied = cxt =>
                {
                    cxt.Response.StatusCode = 403;
                    return Task.CompletedTask;
                };

                options.Events.OnRedirectToLogout = cxt => Task.CompletedTask;
            });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthentication();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapBlazorHub();
                endpoints.MapFallbackToPage("/_Host");
            });
        }
    }
}
使用系统;
使用System.Collections.Generic;
使用System.Linq;
使用System.Threading.Tasks;
使用Microsoft.AspNetCore.Builder;
使用Microsoft.AspNetCore.Components;
使用Microsoft.EntityFrameworkCore;
使用Microsoft.AspNetCore.Hosting;
使用Microsoft.Extensions.Configuration;
使用Microsoft.Extensions.DependencyInjection;
使用Microsoft.Extensions.Hosting;
使用GroupMembersInfo.Data;
使用Microsoft.AspNetCore.Identity;
使用Microsoft.AspNetCore.Components.Authorization;
使用Microsoft.AspNetCore.Components.Server;
命名空间GroupMembersInfo
{
公营创业
{
公共启动(IConfiguration配置)
{
配置=配置;
}
公共IConfiguration配置{get;}
//此方法由运行时调用。请使用此方法将服务添加到容器中。
//有关如何配置应用程序的更多信息,请访问https://go.microsoft.com/fwlink/?LinkID=398940
public void配置服务(IServiceCollection服务)
{
services.AddDbContextPool(
options=>options.UseSqlServer(Configuration.GetConnectionString(“GMIDbConnection”));
services.AddIdentity(options=>options.SignIn.RequireConfirmedAccount=true)
.AddEntityFrameworkStores();
services.AddRazorPages();
AddServerSideBlazor();
services.addScope();
services.AddSingleton();
services.configureApplicationOK(选项=>
{
options.SlidingExpiration=true;
options.Events.OnRedirectToLogin=cxt=>
{
cxt.Response.StatusCode=401;
返回Task.CompletedTask;
};
options.Events.OnRedirectToAccessDenied=cxt=>
{
cxt.Response.StatusCode=403;
返回Task.CompletedTask;
};
options.Events.OnRedirectToLogout=cxt=>Task.CompletedTask;
});
}
//此方法由运行时调用。请使用此方法配置HTTP请求管道。
public void配置(IApplicationBuilder应用程序、IWebHostEnvironment环境)
{
if(env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
其他的
{
app.UseExceptionHandler(“/Error”);
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(端点=>
{
endpoints.MapBlazorHub();
endpoints.MapFallbackToPage(“/_主机”);
});
}
}
}
登录组件代码

@page "/loginPage"

@using Microsoft.AspNetCore.Identity;
@using GroupMembersInfo.Data;

@inject UserManager<IdentityUser> UserManager
@inject SignInManager<IdentityUser> SignInManager
@inject NavigationManager NavigationManager

<h3>Log In</h3>

<div class="row">
    <div class="col-md-12">
        <EditForm Model="@RegisterUserModel" OnValidSubmit="@LogIn">
            <div class="form-group">
                <label>Iser Id: </label>
                <input @bind-value="RegisterUserModel.Email" class="form-control" />
            </div>
            <div class="form-group">
                <label>Password: </label>
                <input @bind-value="RegisterUserModel.Password" class="form-control" />
            </div>
            <div class="form-group">
                <button type="submit">Submit</button>
            </div>
        </EditForm>
    </div>
</div>

@code {
    public RegisterUserModel RegisterUserModel { get; set; } = new RegisterUserModel();

    public async Task LogIn()
    {
        var user = new IdentityUser
        {
            UserName = RegisterUserModel.Email
        };

        user.PasswordHash = SignInManager.UserManager.PasswordHasher.HashPassword(user, RegisterUserModel.Password);

        await SignInManager.SignInAsync(user, isPersistent: false);

        NavigationManager.NavigateTo("/");
    }
}
@page”/loginPage
@使用Microsoft.AspNetCore.Identity;
@使用GroupMembersInfo.Data;
@注入用户管理器用户管理器
@注入SignInManager SignInManager
@注入NavigationManager NavigationManager
登录
Iser Id:
密码:
提交
@代码{
公共RegisterUserModel RegisterUserModel{get;set;}=new RegisterUserModel();
公共异步任务登录()
{
var user=新标识用户
{
用户名=RegisterUserModel.Email
};
user.PasswordHash=SignInManager.UserManager.PasswordHasher.HashPassword(user,RegisterUserModel.Password);
等待SignInManager.SignInAsync(用户,isPersistent:false);
NavigationManager.NavigateTo(“/”);
}
}

问题出在下面两行:await SignInManager.SignInAsync(user, isPersistent: false); NavigationManager.NavigateTo("/");
return NavigationManager.NavigateTo("/");
        await SignInManager.SignInAsync(user, isPersistent: false).ContinueWith(prop =>
        {
            NavigationManager.NavigateTo("/");
        });