【发布时间】:2023-02-07 17:47:09
【问题描述】:
程序.cs 文件:
builder.Services.AddAuthentication("CookieAuthentication").AddCookie("CookieAuthentication", options =>
{
options.LoginPath = "/Home/Index";
options.AccessDeniedPath = "/Login/AccessDenied";
});
// Add services to the container.
builder.Services.AddControllersWithViews();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Login}/{action=Signup}/{id?}");
app.Run();
登录控制器:
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult LoginView(string username, string password)
{
if (!ModelState.IsValid)
{
//Error code here
}
if (!UserExists(username, password))//Check if user exists in Database
{
//Error code here
}
TempData["Username"] = username;
return RedirectToAction("Index", "Home");
//I used breakpoint here and this code runs but doesn't work properly.
}
我还在 Home Controller 上使用了 [Authorize] 属性,以防止用户在未登录的情况下访问它。
【问题讨论】:
-
你说你在 HomeController 上添加了
[Authorize]属性?请务必在 HomeController 的 Index 操作中添加[AllowAnonymous]。因为对于您的网址,它似乎总是重定向到Home/Index。