任务:如果用户未通过身份验证,请转到登录页面!

我希望在每个 Controller 的每个 Action 中都有这种行为。

但是当然我不想在每个 Action 中都有逻辑

if (User == null || User.Identity == null || !User.Identity.IsAuthenticated)
{
    return RedirectToAction("Index","Authentication");
}

这有什么好的做法?

我添加到网络配置:
<authentication mode="Forms">
  <forms loginUrl="~/Authentication" timeout="2880"/>
</authentication>

Controller 有属性 [authorize],除了 AuthenticationController 有 [AllowAnonymous]

但仍然没有重定向到登录页面(只显示错误:HTTP 错误 401.0 - 未经授权)

编辑2:
解决了!

我有
 <remove name="FormsAuthentication" />

在 web.cofig

当我删除这条线时,一切都很好

最佳答案

您应该定义成员资格提供者或为您的系统提供身份的东西。然后你应该为你的 Controller 使用 Authorize 属性。

如果用户未通过身份验证,授权属性会将操作重定向到登录 View 。

关于c# - 如果用户未通过身份验证,请转到登录页面,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35341217/

10-13 06:02