C# 在Asp.NET Core 2中登录

C# 在Asp.NET Core 2中登录,c#,asp.net-core,asp.net-core-2.0,asp.net-core-identity,C#,Asp.net Core,Asp.net Core 2.0,Asp.net Core Identity,关于如何正确登录Asp.NET Core V2的问题。我正在使用ASP.NET标识 下面是我的OnPostAsync()方法。我的代码成功地获取了用户名和pwd,调用了signin manager,并成功地返回了true。我认为正确的登录方式是调用SigninPasswordAsync。一个成功的结果回来了 public async Task<IActionResult> OnPostAsync() { if (!ModelState.IsValid)

关于如何正确登录Asp.NET Core V2的问题。我正在使用ASP.NET标识

下面是我的OnPostAsync()方法。我的代码成功地获取了用户名和pwd,调用了signin manager,并成功地返回了true。我认为正确的登录方式是调用SigninPasswordAsync。一个成功的结果回来了

    public async Task<IActionResult> OnPostAsync()
    {
        if (!ModelState.IsValid)
        {
            return Page();
        }
        var userName = Request.Form["UserName"];
        var pwd = Request.Form["Password"];
        var appUser = new ApplicationUser() { UserName = userName };
        var signin = await _signInManager.PasswordSignInAsync(userName, pwd, true, false);
        if (signin.Succeeded)
        {
            return RedirectToPage("/Account/LoggedIn");
        }
        else
        {
            return RedirectToPage("/Account/Login");
        }
    }

****更新****************************


我正在从Startup.cs文件中添加以下内容:

    public static IConfigurationRoot Configuration { get; set; }
    // 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)
    {
        var builder = new ConfigurationBuilder()
       .SetBasePath(System.IO.Directory.GetCurrentDirectory())
       .AddJsonFile("appsettings.json");

        Configuration = builder.Build();
        services.AddDbContext<PooperAppDbContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

        services.AddIdentity<ApplicationUser, ApplicationRole>()
            .AddEntityFrameworkStores<PooperAppDbContext>()
            .AddDefaultTokenProviders();

        services.AddScoped<SignInManager<ApplicationUser>>();

        services.Configure<IdentityOptions>(options =>
        {
            // Password settings
            options.Password.RequireDigit = true;
            options.Password.RequiredLength = 8;
            options.Password.RequireNonAlphanumeric = false;
            options.Password.RequireUppercase = true;
            options.Password.RequireLowercase = false;
            options.Password.RequiredUniqueChars = 6;

            // Lockout settings
            options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(30);
            options.Lockout.MaxFailedAccessAttempts = 10;
            options.Lockout.AllowedForNewUsers = true;

            // User settings
            options.User.RequireUniqueEmail = true;

        });

        services.ConfigureApplicationCookie(options =>
        {
            // Cookie settings
            options.Cookie.HttpOnly = true;
            options.Cookie.Expiration = TimeSpan.FromDays(150);
            options.LoginPath = "/Account/Login"; // If the LoginPath is not set here, ASP.NET Core will default to /Account/Login
            options.LogoutPath = "/Account/Logout"; // If the LogoutPath is not set here, ASP.NET Core will default to /Account/Logout
            options.AccessDeniedPath = "/Account/AccessDenied"; // If the AccessDeniedPath is not set here, ASP.NET Core will default to /Account/AccessDenied
            options.SlidingExpiration = true;
        });

        services.AddMvc().AddRazorPagesOptions(options =>
        {
            //options.Conventions.AuthorizeFolder("/MembersOnly");
            options.Conventions.AuthorizePage("/Account/Logout");
            options.Conventions.AuthorizePage("/Account/LoggedIn", "PooperBasic, PooperPayer"); // with policy
            //options.Conventions.AllowAnonymousToPage("/Pages/Admin/Login"); // excluded page

            //options.Conventions.AllowAnonymousToFolder("/Public"); // just for completeness
        });

        services.AddAuthorization(options =>
        {
            options.AddPolicy("RequireAdministratorRole", policy => policy.RequireRole("Administrator"));
        });
    }

    // 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();
        }
        else
        {
            var options = new RewriteOptions()
                .AddRedirectToHttps();
        }
        app.UseMvc();
        app.UseAuthentication();
    }
}
publicstaticiconfigurationroot配置{get;set;}
//此方法由运行时调用。使用此方法向容器中添加服务。
//有关如何配置应用程序的更多信息,请访问https://go.microsoft.com/fwlink/?LinkID=398940
public void配置服务(IServiceCollection服务)
{
var builder=new ConfigurationBuilder()
.SetBasePath(System.IO.Directory.GetCurrentDirectory())
.AddJsonFile(“appsettings.json”);
Configuration=builder.Build();
services.AddDbContext(选项=>
options.UseSqlServer(Configuration.GetConnectionString(“DefaultConnection”));
服务.额外性()
.AddEntityFrameworkStores()
.AddDefaultTokenProviders();
services.addScope();
配置(选项=>
{
//密码设置
options.Password.RequireDigit=true;
options.Password.RequiredLength=8;
options.Password.RequireNonAlphanumeric=false;
options.Password.RequireUppercase=true;
options.Password.RequireLowercase=false;
options.Password.RequiredUniqueChars=6;
//锁定设置
options.Lockout.DefaultLockoutTimeSpan=TimeSpan.FromMinutes(30);
options.locket.MaxFailedAccessAttempts=10;
options.locket.AllowedForNewUsers=true;
//用户设置
options.User.RequireUniqueEmail=true;
});
services.configureApplicationOK(选项=>
{
//Cookie设置
options.Cookie.HttpOnly=true;
options.Cookie.Expiration=TimeSpan.FromDays(150);
options.LoginPath=“/Account/Login”;//如果此处未设置LoginPath,ASP.NET Core将默认为/Account/Login
options.LogoutPath=“/Account/Logout”;//如果此处未设置LogoutPath,ASP.NET Core将默认为/Account/Logout
options.AccessDeniedPath=“/Account/AccessDeniedPath”;//如果此处未设置AccessDeniedPath,ASP.NET Core将默认为/Account/AccessDenied
options.SlidingExpiration=true;
});
services.AddMvc().AddRazorPagesOptions(选项=>
{
//options.Conventions.authorized文件夹(“/MembersOnly”);
选项.约定.授权页面(“/Account/Logout”);
options.Conventions.AuthorizePage(“/Account/LoggedIn”,“PooperBasic,PooperPayer”);//带有策略
//options.Conventions.AllowAnonymousToPage(“/Pages/Admin/Login”);//排除的页面
//options.Conventions.AllowAnonymousToFolder(“/Public”);//只是为了完整性
});
services.AddAuthorization(选项=>
{
options.AddPolicy(“RequireAdministratorRole”,policy=>policy.RequireRole(“Administrator”);
});
}
//此方法由运行时调用。使用此方法配置HTTP请求管道。
公共无效配置(IApplicationBuilder应用程序,IHostingEnvironment环境)
{
if(env.IsDevelopment())
{
//app.UseDeveloperExceptionPage();
}
其他的
{
var options=新的重写选项()
.AddRedirectToHttps();
}
app.UseMvc();
app.UseAuthentication();
}
}

您需要在使用MVC之前调用
UseAuthentication
。所有中间件都作为管道的一部分运行,因此在您的情况下,不会在您期望的时候调用身份验证中间件

请参阅,以获得对中间件管道的良好描述


注意:您不需要调用
services.AddScoped()因为这将由
附加属性
处理。

您需要在
使用MVC
之前调用
UseAuthentication
。所有中间件都作为管道的一部分运行,因此在您的情况下,不会在您期望的时候调用身份验证中间件

请参阅,以获得对中间件管道的良好描述


注意:您不需要调用
services.AddScoped()
因为这将由
附加属性
处理。

Configure()
方法中,您不需要在
app.UserMvc()
之前先放置
app.UseAuthentication()
?我也会接受@DavidLiang的答案,但不知道如何接受评论。有没有办法做到这一点?将其标记为有用是很好的。:)在
Configure()
方法中,你不需要在
app.UserMvc()
之前先放置
app.UseAuthentication()
吗?我也会接受@DavidLiang的答案,但不知道如何接受评论。有没有办法做到这一点?将其标记为有用是很好的。:)有乐趣的编程。
    public static IConfigurationRoot Configuration { get; set; }
    // 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)
    {
        var builder = new ConfigurationBuilder()
       .SetBasePath(System.IO.Directory.GetCurrentDirectory())
       .AddJsonFile("appsettings.json");

        Configuration = builder.Build();
        services.AddDbContext<PooperAppDbContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

        services.AddIdentity<ApplicationUser, ApplicationRole>()
            .AddEntityFrameworkStores<PooperAppDbContext>()
            .AddDefaultTokenProviders();

        services.AddScoped<SignInManager<ApplicationUser>>();

        services.Configure<IdentityOptions>(options =>
        {
            // Password settings
            options.Password.RequireDigit = true;
            options.Password.RequiredLength = 8;
            options.Password.RequireNonAlphanumeric = false;
            options.Password.RequireUppercase = true;
            options.Password.RequireLowercase = false;
            options.Password.RequiredUniqueChars = 6;

            // Lockout settings
            options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(30);
            options.Lockout.MaxFailedAccessAttempts = 10;
            options.Lockout.AllowedForNewUsers = true;

            // User settings
            options.User.RequireUniqueEmail = true;

        });

        services.ConfigureApplicationCookie(options =>
        {
            // Cookie settings
            options.Cookie.HttpOnly = true;
            options.Cookie.Expiration = TimeSpan.FromDays(150);
            options.LoginPath = "/Account/Login"; // If the LoginPath is not set here, ASP.NET Core will default to /Account/Login
            options.LogoutPath = "/Account/Logout"; // If the LogoutPath is not set here, ASP.NET Core will default to /Account/Logout
            options.AccessDeniedPath = "/Account/AccessDenied"; // If the AccessDeniedPath is not set here, ASP.NET Core will default to /Account/AccessDenied
            options.SlidingExpiration = true;
        });

        services.AddMvc().AddRazorPagesOptions(options =>
        {
            //options.Conventions.AuthorizeFolder("/MembersOnly");
            options.Conventions.AuthorizePage("/Account/Logout");
            options.Conventions.AuthorizePage("/Account/LoggedIn", "PooperBasic, PooperPayer"); // with policy
            //options.Conventions.AllowAnonymousToPage("/Pages/Admin/Login"); // excluded page

            //options.Conventions.AllowAnonymousToFolder("/Public"); // just for completeness
        });

        services.AddAuthorization(options =>
        {
            options.AddPolicy("RequireAdministratorRole", policy => policy.RequireRole("Administrator"));
        });
    }

    // 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();
        }
        else
        {
            var options = new RewriteOptions()
                .AddRedirectToHttps();
        }
        app.UseMvc();
        app.UseAuthentication();
    }
}