Request.IsAuthenticated does not change view in FormsAuthentication in ASP.NET MVC

I am developing a simple asp.Net MVC application that needs FormsAuthentication,

Model

public class Member
{
    [Required]
    [Display(Name = "Username")]
    public string Username { set; get; }

    [Required]
    [Display(Name = "Password")]
    public string Password { set; get; }

    [Display(Name = "Remember Me?")]
    public bool RemeberMe { set; get; }

    public bool IsValid(string username,string password)
    {
        return (new TestdbEntities()).Members.Any(m => m.Username == username && m.Password == password);
    }
}

      

Controller

[HttpGet]
public ActionResult Login()
{
    return View();
}

[HttpPost]
public ActionResult Login(Models.Member member)
{
    if (ModelState.IsValid)
    {
        if (member.IsValid(member.Username, member.Password))
        {
            FormsAuthentication.SetAuthCookie(member.Username,member.RemeberMe);
            return RedirectToAction("Index","Home");
        }
        else
        {
            ModelState.AddModelError("","Invalid Username/Passowrd!");
        }
    }
    return View(member);
}

      

View

There is a problem that I expect the Login link to change to Logout link when the user is successfully authenticated, but even when I trace, the login is successful but Request.IsAuthenticated

false.

<body>
    <ul class="nav nav-pills">
        <li>
            @Html.ActionLink("Home", "Index", "Home")
        </li>
        <li>
            @if (Request.IsAuthenticated)
            {
                <label>Welcome </label>  @Html.Encode(User.Identity.Name)
                @Html.ActionLink("Signout", "Logout", "Membership")
                @Html.Label(User.Identity.Name.ToString())
            }
            else
            {
                @Html.ActionLink("Login", "Login", "Membership")
            }
        </li>
    </ul>
    <div>
        @RenderBody()
    </div>
</body> 

      

+3


source to share


2 answers


Check your web.config file, you should add <authentication mode="Forms"/>

to tag<system.web>



+1


source


Use the following:



User.Identity.IsAuthenticated()

      

0


source







All Articles