Click here to Skip to main content
15,888,330 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
In first run my code work good but for second run my login page redirect to login page again but that can not redirect to home page .I trace this code and in trace i knowed that it (Request.IsAuthenticated) return false .

This is my models code :
XML
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity;
using Portal.Models;
using System.Linq;
using System.Web.Http;

namespace Portal.Models
{
    public partial class ViewUserDB
    {
        [Required(ErrorMessage = "Please Enter Email Address")]
        [RegularExpression(".+@.+\\..+", ErrorMessage = "Please Enter Correct Email Address")]
        [Display(Name = "User name")]
        public string Username { get; set; }

        [Required(ErrorMessage = "Please Enter Password")]
        [StringLength(int.MaxValue, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
        [DataType(DataType.Password)]
        [Display(Name = "Password")]
        public string Password { get; set; }

        [Required(ErrorMessage = "Please Enter Confirm Password")]
        [DataType(DataType.Password)]
        [Display(Name = "Confirm password")]
        [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
        public string ConfirmPassword { get; set; }

        [Required(ErrorMessage = "Please Enter your first name")]
        [Display(Name = "first name")]
        public string Firstname { get; set; }

        [Required(ErrorMessage = "Please Enter your lastname")]
        [Display(Name = "last name")]
        public string Lastname { get; set; }
        public string XmlField { get; set; }
        public Nullable<bool> Deleted { get; set; }
        public Nullable<bool> Hidden { get; set; }
        public Nullable<byte> Status { get; set; }
        public Nullable<int> RoleID { get; set; }
        public Nullable<int> ParentID { get; set; }
        public Nullable<long> Score { get; set; }
        public Nullable<System.DateTime> RegisterDate { get; set; }
        public Nullable<System.DateTime> LastLogDate { get; set; }
        public Nullable<System.DateTime> UpdateDate { get; set; }
        public string Picture { get; set; }
        public Nullable<int> VisitorID { get; set; }
        public Nullable<int> SiteID { get; set; }
        public string NationalCode { get; set; }
        public Nullable<int> CityID { get; set; }

        public bool AddRegister(string _username, string _firstname, string _lastname, string _password)
        {
            MPortalContext db1 = new MPortalContext();
            var user = db1.WebSite_UserDB.Where(x => x.Username == _username).ToList();
            if (user.Count > 0) return false;
            using (var db = new MPortalContext())
            {
                try
                {
                    if (_password.Length >= 6)
                    {
                        WebSite_UserDB ud = new WebSite_UserDB
                         {
                             Username = _username,
                             Firstname = _firstname,
                             Lastname = _lastname,
                             Password = SHA1.Encode(_password),
                             ParentID = 0,
                             RegisterDate = DateTime.Now,
                             Score = 0,
                             RoleID = 99
                         };
                        db.WebSite_UserDB.Add(ud);
                        db.SaveChanges();
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }
                catch (Exception ex)
                {
                    var E = ex.InnerException;
                    return false;
                }
            }
        }
    }
    public partial class LoginWebSite_UserDB
    {
        public int UserID { get; set; }
        [Required]
        [Display(Name = "User name")]
        public string Username { get; set; }
        [Required]
        [DataType(DataType.Password)]
        [Display(Name = "Password")]
        public string Password { get; set; }
        public string Firstname { get; set; }
        public string Lastname { get; set; }
        public string XmlField { get; set; }
        public Nullable<bool> Deleted { get; set; }
        public Nullable<bool> Hidden { get; set; }
        public Nullable<byte> Status { get; set; }
        public Nullable<int> RoleID { get; set; }
        public Nullable<int> ParentID { get; set; }
        public Nullable<long> Score { get; set; }
        public Nullable<System.DateTime> RegisterDate { get; set; }
        public Nullable<System.DateTime> LastLogDate { get; set; }
        public Nullable<System.DateTime> UpdateDate { get; set; }
        public string Picture { get; set; }
        public Nullable<int> VisitorID { get; set; }
        public Nullable<int> SiteID { get; set; }
        public string NationalCode { get; set; }
        public Nullable<int> CityID { get; set; }
        public bool IsValid(string _username, string _password)
        {
            using (var db = new MPortalContext())
            {
                var list = db.WebSite_UserDB.Where(x => x.Username == _username).ToList();
                if (list.Count > 0)
                {
                    if (list[0].Password == SHA1.Encode(_password))
                    {
                        return true;
                    }
                }
            }
            return false;
        }
    }


    public partial class WebSite_UserDB
    {
        public int UserID { get; set; }
        public string Username { get; set; }
        public string Password { get; set; }
        public string Firstname { get; set; }
        public string Lastname { get; set; }
        public string XmlField { get; set; }
        public Nullable<bool> Deleted { get; set; }
        public Nullable<bool> Hidden { get; set; }
        public Nullable<byte> Status { get; set; }
        public Nullable<int> RoleID { get; set; }
        public Nullable<int> ParentID { get; set; }
        public Nullable<long> Score { get; set; }
        public Nullable<System.DateTime> RegisterDate { get; set; }
        public Nullable<System.DateTime> LastLogDate { get; set; }
        public Nullable<System.DateTime> UpdateDate { get; set; }
        public string Picture { get; set; }
        public Nullable<int> VisitorID { get; set; }
        public Nullable<int> SiteID { get; set; }
        public string NationalCode { get; set; }
        public Nullable<int> CityID { get; set; }
    }
}

This is my layout :
C#
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <title>@ViewBag.Title</title>
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")
</head>
<body>
    <div style="width: auto; background-color: #728ea7;">
        @if (Request.IsAuthenticated) {
            @Html.Encode(User.Identity.Name)
            @Html.ActionLink("Sign Out", "Logout", "User")
        }
        else {
            @Html.ActionLink("Register", "Register", "User")
            <span> | </span>
            @Html.ActionLink("Sign In", "Login", "User")
        }
    </div>
 
    @RenderBody()
 
    @Scripts.Render("~/bundles/jquery")
    @RenderSection("scripts", required: false)
</body>
</html>

This is my Login:
@model Portal.Models.LoginWebSite_UserDB

@{
    ViewBag.Title = "Login";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
@using (Html.BeginForm())
{
    @Html.ValidationSummary(true, "Login failed. Check your login details.");
    <div>
        <fieldset>
            <legend>Login</legend>
            <div class="editor-label">
                User name
            </div>
            <div class="editor-field">
                @Html.TextBoxFor(u => u.Username)
                @Html.ValidationMessageFor(u => u.Username)
            </div>
            <div class="editor-label">
                Password
            </div>
            <div class="editor-field">
                @Html.PasswordFor(u => u.Password)
                @Html.ValidationMessageFor(u => u.Password)
            </div>
            <input type="submit" value="Log In" />
        </fieldset>
    </div>
}

This is my controller :
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using Portal.Models;

namespace Portal.Controllers
{
    public class UserController : Controller
    {

        //
        // GET: /User/

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

        [HttpPost]
        public ActionResult Login(Models.LoginWebSite_UserDB user)
        {
            
            if (ModelState.IsValid)
            {
                if (user.IsValid(user.Username, user.Password))
                {
                    return RedirectToAction("Index", "Home");
                }
                else
                {
                    ModelState.AddModelError("", "Login data is incorrect!");
                }
            }
            return View();
        }
        public ActionResult Logout()
        {
            FormsAuthentication.SignOut();
            return RedirectToAction("Index", "Home");
        }
        

        [HttpGet]
        public ActionResult Register()
        {
            return View();
        }
        
        [HttpPost]
        public ActionResult Register(Models.ViewUserDB mRegister)
        {
            Models.ViewUserDB wu = new Models.ViewUserDB();
            if (mRegister.ConfirmPassword != mRegister.Password)
            {
                TempData["UnSuccess"] = "Your register unsuccess";
                return View();
            }
            if (wu.AddRegister(mRegister.Username, mRegister.Firstname, mRegister.Lastname, mRegister.Password))
            {
                    ViewData["Success"] = "Your register success";
                    return View();
            }
            else
            {
                    TempData["UnSuccess"] = "This user name is exist";
                    return View();
            }
        }

    }
}
Posted
Updated 29-Dec-13 23:36pm
v2

Thought you have missing the authentication cookie setter
C#
System.Web.Security.FormsAuthentication.SetAuthCookie(user.Username, false);
after
if (user.IsValid(user.Username, user.Password))
 
Share this answer
 
This is a very late response.
But the identity inside the USER should be created with the authenticationtype set to some value not left empty.
 
Share this answer
 
This is a very late response. But I would recommend this link:


Four Easy Steps to Set Up OWIN for Form-authentication[^]
 
Share this answer
 
Comments
Richard Deeming 9-Mar-15 16:48pm    
You've been here over 10 years - plenty long enough to know how we feel about people resurrecting old, solved questions!

Particularly as you've resurrected the same question twice. This starts to look like rep-hunting, which is considered abuse.
Assil 9-Mar-15 16:55pm    
I did not intend to do that, and I just noticed that I had answered that before..
I was searching around for something else when I came across this and felt like I could help..
No abuse and I did not even know that person..
I hope you feel better now that you down-voted me,

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900