Request.IsAuthenticated在登录时始终返回false

时间:2014-11-24 11:23:44

标签: asp.net-mvc asp.net-mvc-4 authentication razor

我使用以下代码登录用户 -

    [HttpPost]
    [AllowAnonymous]
    public void Login(LoginModel model, string returnUrl)
    {
        if (ModelState.IsValid)
        {
            WebSecurity.Login(model.EMail, model.Password, persistCookie: model.RememberMe);
            return;
        }

        ModelState.AddModelError("", "The user name or password provided is incorrect.");
        return;
    }

登录后,在我的布局文件中,我正在检查他是否经过身份验证 -

    @if (!Request.IsAuthenticated)
    {
         <div>not authenticated</div>
    }

    @if (Request.IsAuthenticated)
    {
         <div>authenticated</div>
    }

但是,不知怎的,这总是回归&#34;未经过身份验证&#34;。当我注册然后登录时,这段代码工作正常。任何人都可以在这里提出可能存在的问题吗?

注册代码 -

    [HttpPost]
    [AllowAnonymous]
    public void Register(RegisterModel model)
    {
        if (ModelState.IsValid)
        {
            // Attempt to register the user
            try
            {
                WebSecurity.CreateUserAndAccount(model.EMail, model.Password);
                WebSecurity.Login(model.EMail, model.Password);
            }
            catch (MembershipCreateUserException e)
            {
                ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
            }
        }

        return;
    }

3 个答案:

答案 0 :(得分:4)

只需在Web.config

中添加以下代码即可
self.scrollView.alwaysBounceVertical = true

<authentication mode="Forms">
  <forms loginUrl="~/_Login/Login" timeout="30" />
</authentication>

我希望这会有所帮助

答案 1 :(得分:1)

您必须使用WebSecurity类:

 @if (!WebSecurity.IsAuthenticated)
    {
         <div>not authenticated</div>
    }

    @if (WebSecurity.IsAuthenticated)
    {
         <div>authenticated</div>
    }

请参阅here (Adding Security and Membership to an ASP.NET Web Pages (Razor) Site)

或者您可以尝试:

@if (HttpContext.Current.User.Identity.IsAuthenticated)
{
 // user is logged in
}
else
{
 // user is not loggged in
}

UPDATE:

并且在登录操作中如果登录成功则以这种方式检查:

[HttpPost]
[AllowAnonymous]
public void Login(LoginModel model, string returnUrl)
{
    if (ModelState.IsValid && WebSecurity.Login(model.EMail, model.Password, persistCookie: model.RememberMe))
    {
     // login successful
    }
    else
    {
     // login failed
    }
}

答案 2 :(得分:0)

此MSDN链接可能有所帮助。 https://msdn.microsoft.com/en-us/library/ff647070.aspx

if (Membership.ValidateUser(userName.Text, password.Text))
{
    if (Request.QueryString["ReturnUrl"] != null)
    {
        FormsAuthentication.RedirectFromLoginPage(userName.Text, false);
    }
    else
    {
        FormsAuthentication.SetAuthCookie(userName.Text, false);
    }
}
else
{
    Response.Write("Invalid UserID and Password");
}