Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/logging/2.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
使用Identity Core登录ASP.Net Core 2.1后立即添加重定向_Asp.net_.net_Asp.net Core_Asp.net Identity_Claims Based Identity - Fatal编程技术网

使用Identity Core登录ASP.Net Core 2.1后立即添加重定向

使用Identity Core登录ASP.Net Core 2.1后立即添加重定向,asp.net,.net,asp.net-core,asp.net-identity,claims-based-identity,Asp.net,.net,Asp.net Core,Asp.net Identity,Claims Based Identity,我试图在使用Identity Core登录.Net Core 2.1应用程序后立即实现重定向 重定向取决于登录用户的角色 我得到一个空引用异常 我阅读了一些堆栈溢出问题和Git问题,了解到这是因为用户在登录后没有立即存储到数据库中: var result =await _signInManager.PasswordSignInAsync(Input.Email, Input.Password, Input.RememberMe, lockoutOnFailure: true).Result;

我试图在使用Identity Core登录.Net Core 2.1应用程序后立即实现重定向

重定向取决于登录用户的角色

我得到一个空引用异常

我阅读了一些堆栈溢出问题和Git问题,了解到这是因为用户在登录后没有立即存储到数据库中:

var result =await _signInManager.PasswordSignInAsync(Input.Email, Input.Password, Input.RememberMe, lockoutOnFailure: true).Result;
我尝试了以下操作以检索登录用户的角色:

方法1:

string userRole =_signInManager.Context.User.FindFirst(ClaimTypes.Role).Value;
方法2:

要确定给定角色中是否存在用户,请执行以下操作:

User.IsInRole("RoleName")
方法3:

_userManager.GetClaimsAsync(user)
在所有情况下,我都会得到一个空引用异常; 我理解这是因为请求未完成

然而,我不明白出了什么问题

需要指导

这是我的startup.cs:

 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.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlServer(
                    Configuration.GetConnectionString("DefaultConnection")));

            services.AddIdentity<IdentityUser,IdentityRole>()
                .AddEntityFrameworkStores<ApplicationDbContext>();

            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
                
            });

            services.ConfigureApplicationCookie(options =>
            {
                // Cookie settings  
                options.Cookie.HttpOnly = true;
                options.ExpireTimeSpan = TimeSpan.FromMinutes(30);
                options.LoginPath = "/Identity/Account/Login"; 
                options.LogoutPath = "/Identity/Account/Logout"; 
                options.AccessDeniedPath = "/Identity/Account/AccessDenied"; 
                options.SlidingExpiration = true;
            });

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        
        }

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

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

            app.UseAuthentication();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{Controller=Home}/{action=Index}/{id?}");
            });
        }
    }
公共类启动
{
公共启动(IConfiguration配置)
{
配置=配置;
}
公共IConfiguration配置{get;}
//此方法由运行时调用。请使用此方法将服务添加到容器中。
public void配置服务(IServiceCollection服务)
{
services.AddDbContext(选项=>
options.UseSqlServer(
GetConnectionString(“DefaultConnection”);
服务.额外性()
.AddEntityFrameworkStores();
配置(选项=>
{
//此lambda确定给定请求是否需要非必要cookie的用户同意。
options.checkApprovered=context=>true;
options.MinimumSameSitePolicy=SameSiteMode.None;
});
services.configureApplicationOK(选项=>
{
//Cookie设置
options.Cookie.HttpOnly=true;
options.ExpireTimeSpan=TimeSpan.FromMinutes(30);
options.LoginPath=“/Identity/Account/Login”;
options.LogoutPath=“/Identity/Account/Logout”;
options.AccessDeniedPath=“/Identity/Account/AccessDenied”;
options.SlidingExpiration=true;
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
//此方法由运行时调用。请使用此方法配置HTTP请求管道。
公共无效配置(IApplicationBuilder应用程序,IHostingEnvironment环境)
{
if(env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
其他的
{
app.UseExceptionHandler(“/Home/Error”);
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseAuthentication();
app.UseMvc(路由=>
{
routes.MapRoute(
名称:“默认”,
模板:“{Controller=Home}/{action=Index}/{id?}”);
});
}
}
登录-标识核心的页面控制器:

public async Task<IActionResult> OnPostAsync(string returnUrl = null)
{
    returnUrl = returnUrl ?? Url.Content("return path");
    
    if (ModelState.IsValid)
    {

        var result = _signInManager.PasswordSignInAsync(Input.Email, Input.Password, Input.RememberMe, lockoutOnFailure: true).Result;
        if (result.Succeeded)
        {
            var usera = User.IsInRole("Role1");
            var users = User.IsInRole("Role2");

            //string userEmail = _signInManager.Context.User.FindFirst(ClaimTypes.Name).Value;
            //string userRole = _signInManager.Context.User.FindFirst(ClaimTypes.Role).Value;
            if (User.IsInRole("Admin"))
            {
                return RedirectToAction("path1");
            }
            else if (User.IsInRole("Supervisor"))
            {
               return RedirectToAction("path2");
            }
            else if (User.IsInRole("Member"))
            {
              return RedirectToAction("path3");
            }
            else
            {
                 return RedirectToPage("/Identity/Account/AccessDenied");
            }
        }
        if (result.RequiresTwoFactor)
        {
            return RedirectToPage("./LoginWith2fa", new { ReturnUrl = returnUrl, RememberMe = Input.RememberMe });
        }
        if (result.IsLockedOut)
        {
            _logger.LogWarning("User account locked out.");
            return RedirectToPage("./Lockout");
        }
        else
        {
            ModelState.AddModelError(string.Empty, "Invalid login attempt.");
            return Page();
        }
    }

   
    return Page();
}
PostAsync上的公共异步任务(字符串returnUrl=null) { returnUrl=returnUrl??Url.Content(“返回路径”); if(ModelState.IsValid) { var result=_signInManager.PasswordSignInAsync(Input.Email,Input.Password,Input.RememberMe,lockoutOnFailure:true); if(result.successed) { var usera=User.IsInRole(“Role1”); var users=User.IsInRole(“Role2”); //字符串userEmail=\u signInManager.Context.User.FindFirst(ClaimTypes.Name).Value; //字符串userRole=\u signInManager.Context.User.FindFirst(ClaimTypes.Role).Value; if(User.IsInRole(“Admin”)) { 返回重定向到操作(“路径1”); } else if(用户权限(“主管”)) { 返回重定向到操作(“路径2”); } else if(User.IsInRole(“成员”)) { 返回重定向到操作(“路径3”); } 其他的 { 返回重定向Topage(“/Identity/Account/AccessDenied”); } } if(结果要求系数) { return RedirectToPage(“./LoginWith2fa”,新的{ReturnUrl=ReturnUrl,RememberMe=Input.RememberMe}); } 如果(结果IsLockedOut) { _logger.LogWarning(“用户帐户锁定”); 返回重定向Topage(“/锁定”); } 其他的 { AddModelError(string.Empty,“登录尝试无效”); 返回页(); } } 返回页(); }
如果您想在
\u signInManager.PasswordSignInAsync
之后获得角色信息,您可以直接在数据库中查询:

var user = await _signInManager.UserManager.FindByEmailAsync(Input.Email);
IList<string> roles = await _signInManager.UserManager.GetRolesAsync(user);
var user=await\u signInManager.UserManager.findbyemailsync(Input.Email);
IList roles=await _signInManager.UserManager.GetRolesAsync(用户);