[英]Unable to redirect to my local page in asp dot net core
I am new to asp.net core
.我是
asp.net core
新手。 I have used Identity for login and registration.我已经使用身份登录和注册。 I am trying to redirect to my page after successful login.
我试图在成功登录后重定向到我的页面。
public async Task<IActionResult> OnPostAsync(string returnUrl = null)
{
returnUrl = Url.Content("~/Home/Index");
if (ModelState.IsValid)
{
// This doesn't count login failures towards account lockout
// To enable password failures to trigger account lockout, set lockoutOnFailure: true
var result = await _signInManager.PasswordSignInAsync(Input.Email, Input.Password, Input.RememberMe, lockoutOnFailure: false);
if (result.Succeeded)
{
_logger.LogInformation("User logged in.");
return LocalRedirect(returnUrl);
}
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();
}
}
// If we got this far, something failed, redisplay form
return Page();
}
Below is my startup file in which I have done some configurations下面是我的启动文件,我在其中做了一些配置
Startup.cs启动文件
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseAuthentication();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
endpoints.MapRazorPages();
});
}
Update 1更新 1
Below is my Login.cshtml.cs
下面是我的
Login.cshtml.cs
namespace DemoLogin.Areas.Identity.Pages.Account
{
[AllowAnonymous]
public class LoginModel : PageModel
{
private readonly UserManager<DemoLoginUser> _userManager;
private readonly SignInManager<DemoLoginUser> _signInManager;
private readonly ILogger<LoginModel> _logger;
public LoginModel(SignInManager<DemoLoginUser> signInManager,
ILogger<LoginModel> logger,
UserManager<DemoLoginUser> userManager)
{
_userManager = userManager;
_signInManager = signInManager;
_logger = logger;
}
[BindProperty]
public InputModel Input { get; set; }
public IList<AuthenticationScheme> ExternalLogins { get; set; }
public string ReturnUrl { get; set; }
[TempData]
public string ErrorMessage { get; set; }
public class InputModel
{
[Required]
[EmailAddress]
public string Email { get; set; }
[Required]
[DataType(DataType.Password)]
public string Password { get; set; }
[Display(Name = "Remember me?")]
public bool RememberMe { get; set; }
}
public async Task OnGetAsync(string returnUrl = null)
{
if (!string.IsNullOrEmpty(ErrorMessage))
{
ModelState.AddModelError(string.Empty, ErrorMessage);
}
returnUrl = returnUrl ?? Url.Content("~/");
// Clear the existing external cookie to ensure a clean login process
await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme);
ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
ReturnUrl = returnUrl;
}
public async Task<IActionResult> OnPostAsync(string returnUrl = null)
{
returnUrl = returnUrl ?? Url.Content("~/");
if (ModelState.IsValid)
{
// This doesn't count login failures towards account lockout
// To enable password failures to trigger account lockout, set lockoutOnFailure: true
var result = await _signInManager.PasswordSignInAsync(Input.Email, Input.Password, Input.RememberMe, lockoutOnFailure: false);
if (result.Succeeded)
{
_logger.LogInformation("User logged in.");
return LocalRedirect(returnUrl);
}
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();
}
}
// If we got this far, something failed, redisplay form
return Page();
}
}
}
I have registered a user and then tried to log in it.我已经注册了一个用户,然后尝试登录它。 But I am not redirecting to my page
~/Home/Index
但我没有重定向到我的页面
~/Home/Index
I think I know the problem, did you add the [Authorize]
attribute to your Index method?我想我知道问题所在,您是否将
[Authorize]
属性添加到您的 Index 方法中?
Here is the solution.这是解决方案。
change the order to:将顺序更改为:
app.UseAuthentication();
app.UseAuthorization();
Since there are a lot of errors in your project, I suggest you create a new project and follow my steps.由于你的项目有很多错误,建议你新建一个项目,按照我的步骤操作。 It is very simple.
这很简单。
Step1:(change the Authentication
):步骤1:(更改
Authentication
):
Step2:(Click the project Add
and then click New Scaffolded Item
.): Step2:(点击项目
Add
然后点击New Scaffolded Item
。):
Step3:(chooes Identity then add):第三步:(选择身份然后添加):
Step4(override all files then add): Step4(覆盖所有文件然后添加):
Last :migration and run project.Register first and then log in.最后:迁移并运行项目。先注册然后登录。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.