C# ASP.Net核心Cookies身份验证重定向到登录
我正在尝试使用cookies设置身份验证,但C# ASP.Net核心Cookies身份验证重定向到登录,c#,authentication,cookies,asp.net-core,asp.net-core-2.0,C#,Authentication,Cookies,Asp.net Core,Asp.net Core 2.0,我正在尝试使用cookies设置身份验证,但SignInAsync似乎不起作用 我的符号方法至少在目前是这样的: [HttpPost] public async Task<IActionResult> Login(string username, string password) { if (username != "foo" || password != "bar") { return View(); } //Sign in
SignInAsync
似乎不起作用
我的符号方法至少在目前是这样的:
[HttpPost]
public async Task<IActionResult> Login(string username, string password)
{
if (username != "foo" || password != "bar")
{
return View();
}
//Sign in
var claims = new List<Claim>
{
new Claim("name", "admin")
};
var userIdentity = new ClaimsIdentity(claims, "login");
ClaimsPrincipal principal = new ClaimsPrincipal(userIdentity);
await HttpContext.SignInAsync(principal);
//Redirect
return RedirectToAction("home");
}
我遗漏了什么,或者如何调试/获取有关出错原因的更多信息?根据Tratcher的评论,使用
app.UseAuthentication()代码>在app.UseMvc()之前
根据Tratcher的评论,使用app.UseAuthentication()代码>在app.UseMvc()之前代码>app.UseAuthentication();在UseMvc.app.UseAuthentication()之前;在UseMvc之前。
public class Startup
{
// 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.AddMvc();
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.LoginPath = "/admin/login/";
});
}
// 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.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=home}/{action=index}/{id?}");
});
app.UseAuthentication();
}
}