asp.net-core - 登录后也能进入登录页面
问题描述
我正在使用启用了个人用户身份验证的默认模型-视图-控制器模板。问题是当我登录后,我仍然可以进入登录页面。如何预防?
解决方案
您可以自定义中间件以在用户登录并访问登录页面时重定向。
重定向中间件.cs
public class RedirectMiddleware
{
private readonly RequestDelegate _next;
public RedirectMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
if(context.Request.Path == "/Identity/Account/Login")
{
if (context.User.Identity.IsAuthenticated)
{
context.Response.Redirect("/Home/Index");
}
}
await _next.Invoke(context);
}
}
启动.cs
app.UseMiddleware<RedirectMiddleware>();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
endpoints.MapRazorPages();
});
或者
直接在 Login OnGetAsync Handler 中做重定向:
public async Task OnGetAsync(string returnUrl = null)
{
if (!string.IsNullOrEmpty(ErrorMessage))
{
ModelState.AddModelError(string.Empty, ErrorMessage);
}
if (User.Identity.IsAuthenticated)
{
Response.Redirect("/Home/Index");
}
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;
}
推荐阅读
- jquery - 平滑引导列下降
- scala - Spark 提交并行作业
- if-statement - 在 CLIPS 中使用 if-then-else 和事实
- jquery - 在 React 应用程序中无法弄清楚 Spotify 的授权
- android-studio - com.android.support:appcompat-v7:27.1.1 与 media-compat:25.2.0 不匹配
- python-3.x - 减少火花返回字典而不是数据帧中的操作
- git - 合并来自拉取请求的单个提交
- python - Python 子类的 Pythonic 方式
- python - 使用 Python Zeep 内省 WSDL
- php - 当我尝试将查询(插入)插入到 if 条件时,然后双插入?