Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/316.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中的HttpContext.SignOutAsync()方法调用引发了响应已启动异常_C#_Azure_Blazor Server Side_Azure Authentication - Fatal编程技术网

C# Blazor中的HttpContext.SignOutAsync()方法调用引发了响应已启动异常

C# Blazor中的HttpContext.SignOutAsync()方法调用引发了响应已启动异常,c#,azure,blazor-server-side,azure-authentication,C#,Azure,Blazor Server Side,Azure Authentication,我正在尝试在ASP.NET core Blazor服务器应用程序中使用HttpContext.SignOutAsync()注销当前用户。调用HttpContext.SignOutAsync()时引发异常。有人知道如何解决这个问题吗?提前谢谢。以下是例外情况的详细信息: 消息: 响应已开始 堆栈跟踪: 在Microsoft.AspNetCore.Server.IIS.Core.IISHttpContext.OnStarting(Func2回调,对象状态)在Microsoft.AspNetCore.

我正在尝试在ASP.NET core Blazor服务器应用程序中使用HttpContext.SignOutAsync()注销当前用户。调用HttpContext.SignOutAsync()时引发异常。有人知道如何解决这个问题吗?提前谢谢。以下是例外情况的详细信息:

消息:

响应已开始

堆栈跟踪:

在Microsoft.AspNetCore.Server.IIS.Core.IISHttpContext.OnStarting(Func
2回调,对象状态)在Microsoft.AspNetCore.Server.IIS.Core.IISHttpContext.Microsoft.AspNetCore.Http.Features.IHttpResponseFeature.OnStarting(Func
2回调,对象状态) 在Microsoft.AspNetCore.Http.DefaultHttpResponse.OnStarting(Func
2回调,对象状态)在Microsoft.AspNetCore.Http.HttpResponse.OnStarting(Func
1回调)上 在Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler.InitializeHandlerAsync()中 在Microsoft.AspNetCore.Authentication.AuthenticationHandler
1.d_u42.MoveNext()中,在System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()中,在System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(任务任务任务)中,在System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务任务任务任务)中位于Microsoft.AspNetCore.Authentication.AuthenticationHandlerProvider.d_u5.MoveNext()的System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()的System.Runtime.CompilerServices.TaskWaiter.ThrowForNonSuccess(任务任务任务)的System.Runtime.CompilerServices.TaskWaiter.HandleNonSuccessAndDebuggerNotification(任务任务任务任务)at System.Runtime.CompilerServices.TaskAwaiter
1.GetResult() 在Microsoft.AspNetCore.Authentication.AuthenticationService.d_u17.MoveNext()中 在System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()中 at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(任务任务) 在System.Runtime.CompilerServices.TaskWaiter.HandleNonSuccessAndDebuggerNotification(任务任务)中 在d:\ScrumPortal\Impersonateuser\scrum portal\ScrumPortal.Application\Base\Common.ImpersonateSerbase.ImpersonateLogin.d_u0.MoveNext()中的d:\ScrumPortal\Impersonateuser\scrum portal\ScrumPortal.Application\Base\Common\ImpersonateSerbase.cs:第130行

内部异常:

空的

Startup.cs

           services.AddAuthentication(auth => {
            auth.DefaultScheme = AzureADDefaults.AuthenticationScheme;
            auth.DefaultChallengeScheme = AzureADDefaults.OpenIdScheme;
            auth.DefaultSignInScheme = AzureADDefaults.AuthenticationScheme;
            }).AddAzureAD(options => this.Configuration.Bind("AzureAd", options)).AddCookie(CookieAuthenticationDefaults.AuthenticationScheme,
            options =>
            {
                options.LoginPath = "/signin";
                options.SlidingExpiration = true;
                options.ExpireTimeSpan = new TimeSpan(7, 0, 0, 0);
            });
        services.Configure<OpenIdConnectOptions>(AzureADDefaults.OpenIdScheme,
            options =>
            {
                Configuration.Bind("AzureAd", options);
                options.Events = new OpenIdConnectEvents
                {
                    OnTokenValidated = ctx =>
                    {
                        ClaimsIdentity identity = (ClaimsIdentity)ctx.Principal.Identity;
                        var emailid = identity.Name;
                        var username = identity.Claims.FirstOrDefault(x => x.Type == "name").Value;
                        var res = new LoginUserModel().GetAuthenticatedUserDetails(emailid);
                        if (res != null && res.UserId > 0)
                        {
                            var claims = new LoginUserModel().AddUserClaims(res);
                            identity.AddClaims(claims);
                        }
                        else
                        {
                            ctx.Properties.RedirectUri = "/unauthorized";
                            return Task.FromResult(0);
                        }

                        return Task.FromResult(ctx);
                    }
                };
            });
        services.AddMvc(config =>
        {
            var policy = new AuthorizationPolicyBuilder()
                         .RequireAuthenticatedUser()
                         .Build();
            config.Filters.Add(new AuthorizeFilter(policy));
            config.EnableEndpointRouting = false;
        });
    public partial class ImpersonateLogin : PageModel
    {
        
        public async Task<IActionResult> ImpersonateBtnClick(string impersonateUserId, HttpContext httpcontext)
        {
            string returnUrl = "~/";
            try
            {                    
                string schema = CookieAuthenticationDefaults.AuthenticationScheme;
                await httpcontext.SignOutAsync(schema);
                CommonModel model = new CommonModel();
                int impersonateUser = 0;
                int currentUser = 0;
                int.TryParse(impersonateUserId, out impersonateUser);
                var result = model.GetUserDetailsForImpersonate(impersonateUser);
                if (result != null)
                {
                    bool impersonateUserCheck = (currentUser == impersonateUser) ? false : true;
                    var claims = new System.Collections.Generic.List<Claim>
            {
             new Claim(SessionInfo.RoleId.ToString(), result.RoleId.ToString()),
             new Claim(SessionInfo.EmailId.ToString(), result.EmailId),
             new Claim(SessionInfo.EmployeeName.ToString(), result.DisplayName),
             new Claim(SessionInfo.UserId.ToString(), impersonateUserId.ToString()),
             new Claim(SessionInfo.IsImpersonateUser.ToString(), impersonateUserCheck.ToString().ToLower()),
             new Claim(SessionInfo.CurrentUserId.ToString(), currentUser.ToString()),
             new Claim(SessionInfo.HRRoleId.ToString(), result.HrRoleId.ToString()),
             new Claim(SessionInfo.HRUserId.ToString(), result.HrUserId.ToString()),
            };

                    var claimsIdentity = new ClaimsIdentity(claims, schema);
                    await httpcontext.SignInAsync(schema, new ClaimsPrincipal(claimsIdentity));
                }                   
            }
            catch (Exception ex)
            {

            }

            return LocalRedirect(returnUrl);
        }
    }
services.AddAuthentication(auth=>{
auth.DefaultScheme=AzureADDefaults.AuthenticationScheme;
auth.DefaultChallengeScheme=AzureADDefaults.OpenIdScheme;
auth.defaultSignenscheme=azureAddFaults.AuthenticationScheme;
}).AddAzureAD(options=>this.Configuration.Bind(“AzureAd”,options)).AddCookie(CookieAuthenticationDefaults.AuthenticationScheme,
选项=>
{
options.LoginPath=“/sign”;
options.SlidingExpiration=true;
options.ExpireTimeSpan=新的时间跨度(7,0,0,0);
});
services.Configure(AzureADDefaults.OpenIdScheme,
选项=>
{
绑定(“AzureAd”,选项);
options.Events=新的OpenIdConnectEvents
{
OnTokenValidated=ctx=>
{
ClaimsIdentity identity=(ClaimsIdentity)ctx.Principal.identity;
var emailid=identity.Name;
var username=identity.Claims.FirstOrDefault(x=>x.Type==“name”).Value;
var res=new LoginUserModel().GetAuthenticatedUserDetails(emailid);
如果(res!=null&&res.UserId>0)
{
var claims=new LoginUserModel().AddUserClaims(res);
身份。添加索赔(索赔);
}
其他的
{
ctx.Properties.RedirectUri=“/unauthorized”;
返回Task.FromResult(0);
}
返回任务.FromResult(ctx);
}
};
});
services.AddMvc(配置=>
{
var policy=new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()文件
.Build();
config.Filters.Add(新的授权过滤器(策略));
config.EnableEndpointRouting=false;
});
基类

           services.AddAuthentication(auth => {
            auth.DefaultScheme = AzureADDefaults.AuthenticationScheme;
            auth.DefaultChallengeScheme = AzureADDefaults.OpenIdScheme;
            auth.DefaultSignInScheme = AzureADDefaults.AuthenticationScheme;
            }).AddAzureAD(options => this.Configuration.Bind("AzureAd", options)).AddCookie(CookieAuthenticationDefaults.AuthenticationScheme,
            options =>
            {
                options.LoginPath = "/signin";
                options.SlidingExpiration = true;
                options.ExpireTimeSpan = new TimeSpan(7, 0, 0, 0);
            });
        services.Configure<OpenIdConnectOptions>(AzureADDefaults.OpenIdScheme,
            options =>
            {
                Configuration.Bind("AzureAd", options);
                options.Events = new OpenIdConnectEvents
                {
                    OnTokenValidated = ctx =>
                    {
                        ClaimsIdentity identity = (ClaimsIdentity)ctx.Principal.Identity;
                        var emailid = identity.Name;
                        var username = identity.Claims.FirstOrDefault(x => x.Type == "name").Value;
                        var res = new LoginUserModel().GetAuthenticatedUserDetails(emailid);
                        if (res != null && res.UserId > 0)
                        {
                            var claims = new LoginUserModel().AddUserClaims(res);
                            identity.AddClaims(claims);
                        }
                        else
                        {
                            ctx.Properties.RedirectUri = "/unauthorized";
                            return Task.FromResult(0);
                        }

                        return Task.FromResult(ctx);
                    }
                };
            });
        services.AddMvc(config =>
        {
            var policy = new AuthorizationPolicyBuilder()
                         .RequireAuthenticatedUser()
                         .Build();
            config.Filters.Add(new AuthorizeFilter(policy));
            config.EnableEndpointRouting = false;
        });
    public partial class ImpersonateLogin : PageModel
    {
        
        public async Task<IActionResult> ImpersonateBtnClick(string impersonateUserId, HttpContext httpcontext)
        {
            string returnUrl = "~/";
            try
            {                    
                string schema = CookieAuthenticationDefaults.AuthenticationScheme;
                await httpcontext.SignOutAsync(schema);
                CommonModel model = new CommonModel();
                int impersonateUser = 0;
                int currentUser = 0;
                int.TryParse(impersonateUserId, out impersonateUser);
                var result = model.GetUserDetailsForImpersonate(impersonateUser);
                if (result != null)
                {
                    bool impersonateUserCheck = (currentUser == impersonateUser) ? false : true;
                    var claims = new System.Collections.Generic.List<Claim>
            {
             new Claim(SessionInfo.RoleId.ToString(), result.RoleId.ToString()),
             new Claim(SessionInfo.EmailId.ToString(), result.EmailId),
             new Claim(SessionInfo.EmployeeName.ToString(), result.DisplayName),
             new Claim(SessionInfo.UserId.ToString(), impersonateUserId.ToString()),
             new Claim(SessionInfo.IsImpersonateUser.ToString(), impersonateUserCheck.ToString().ToLower()),
             new Claim(SessionInfo.CurrentUserId.ToString(), currentUser.ToString()),
             new Claim(SessionInfo.HRRoleId.ToString(), result.HrRoleId.ToString()),
             new Claim(SessionInfo.HRUserId.ToString(), result.HrUserId.ToString()),
            };

                    var claimsIdentity = new ClaimsIdentity(claims, schema);
                    await httpcontext.SignInAsync(schema, new ClaimsPrincipal(claimsIdentity));
                }                   
            }
            catch (Exception ex)
            {

            }

            return LocalRedirect(returnUrl);
        }
    }
public分部类ImpersonateLogin:PageModel
{
公共异步任务ImpersonateBtnClick(字符串IMPERSONATESERID,HttpContext HttpContext)
{
字符串returnUrl=“~/”;
尝试
{                    
字符串模式=CookieAuthenticationDefaults.AuthenticationScheme;
等待httpcontext.SignOutAsync(模式);
CommonModel模型=新的CommonModel();
int-impersonateUser=0;
int currentUser=0;
int.TryParse(impersonateUserId,out impersonateUser);
var result=model.getUserDetailsFrimPersonate(模拟用户);
如果(结果!=null)
{
bool impersonateUserCheck=(currentUser==impersonateUserCheck)?false:true;
var索赔=新System.Collections.Generic.List
{
新声明(SessionInfo.RoleId.ToString(),result.RoleId.ToString()),
新声明(SessionInfo.EmailId.ToString(),result.EmailId),
新声明(SessionInfo.EmployeeName.ToString(),result.DisplayName),
新声明(SessionInfo.UserId.ToString(),impersonateUserId.ToString()),
新声明(SessionInfo.IsImpersonateUser.ToString(),impersonateUserCheck.ToString().ToLower()),
新声明(SessionInfo.CurrentUserId.ToString(),curre