[Solved] User.Identity.IsAuthenticated always returns false in ASP.Net MVC

Last Reply 3 months ago By dharmendr

Posted 3 months ago

hi

in index action I define 2 below line:

bool islogin = User.Identity.IsAuthenticated;
string username = User.Identity.Name;

that I expected it shows in first line True value that means users login succesfully and in second line shows users name but here it shows false in first line and in second line doesnt show user's name.

I create login view in MVC that when users insert username and password and click button it will redirect to index page below are codes:

[HttpGet]
[AllowAnonymous]
public ActionResult Login()
{
    return View();
}
       
[HttpPost]
[AllowAnonymous]
public ActionResult Login(string username,string password,bool rememberme)
{
    var blusers = new UserRepository();
    if (blusers.Exist(username, password))
    {
        FormsAuthentication.SetAuthCookie(username, rememberme);
        return RedirectToAction("Index");
    }
    else {
        ViewBag.Message = "نام کاربری اشتباه است";
    }

    return View();
}

public ActionResult Index()
{
    bool islogin = User.Identity.IsAuthenticated;
    string username = User.Identity.Name;
    GroupRepository blGroup = new GroupRepository();
    ProductRepository blProduct = new ProductRepository();
    var model = new MvcInternetShop.ViewModels.Home.HomeIndexViewModel();
    model.Groups = blGroup.Select();
    model.Products = blProduct.Select();
    //model.BestSellersProducts = blProduct.Select().OrderBy(p => p.FactorItems.Count).Take(6);
    return View(model);
}

best regards

Neda