ASP.NET MVC FormsAuthentication检查用户是否已登录

时间:2015-05-30 14:11:00

标签: asp.net asp.net-mvc forms-authentication

我想仅在用户登录时在视图中显示一些div

我是怎么做到的:

@{
    if (Request.IsAuthenticated)
    // if (User.Identity.IsAuthenticated)
    {
        <div>
            Some content only for logged in users.
        </div>
    }
}

但是Request.IsAuthenticated(和User.Identity.IsAuthenticated总是 true,即使在最初,也就是我从Visual Studio启动网站之后。显然,当用户登录Windows时,它会 me (因为User.Identity.Name返回我的Windows登录信息),但是我需要它来检查用户是否通过FormsAuthentication在网站上进行了身份验证。

这是我的web.config:

<authentication mode="Forms">
  <forms loginUrl="/Account/Login" timeout="2880" />
</authentication>

如何检查用户是否已通过FormsAuthentication登录?

1 个答案:

答案 0 :(得分:6)

如果您要检查用户是否已登录,请使用以下命令:

@if (User.Identity.IsAuthenticated) { /* content */}