In this tutorial, I create a project in ASP.net Web Application using SQL Server. This Project have an user login and registration. I will use the Entity Framework to store user details. Such as username, password, and other columns we required in our ASP.NET Web Application. This article will explain how to use ASP.NET identity to register, login, and log out in your Web Application and use Entity Framework.

I. What is ASP.NET?

ASP.NET is an open source web framework, created by Microsoft, for building modern web apps and services with .NET. ASP.NET is cross platform and runs on Windows, Linux, macOS, and Docker.

Please click HERE about SQL Server.

II. Requirements

Before we start, Please make sure to have installed the following

  • The latest version of Visual Studio
  • SQL Server

Let’s Start;

III. Create ASP.NET Web Application

  • Select File > New > Project.
  • Select ASP.NET Web Application (.Net Framework). Click Next.
  • Configure your new application
    • Project Name “Input your application name”;
    • Location “Location/directory of your application “;
    • Framework “Select the latest one”;
    • Click “
  • Configure your new application
    • Project Name “Input your application name”;
    • Location “Location/directory of your application “;
    • Framework “Select the latest one”;
    • Click “Create Button”;
  • Select the MVC during create web application
    • uncheck the HTTPS // Advanced -> Configure for HTTPS;
    • lastly click “Create Button”

IV. Update NuGet packages

  • What is NuGet Packages
    • NuGet is a package manager that delivers compiled source code (DLLs) and other files (scripts and images) related to code. A NuGet package takes the form of a zip file with the extension . nupkg. This makes adding, updating, and removing libraries easy in Visual Studio applications.
  • Then click Updates
    • Select all packages
    • And click Update

V. Create SQL Database and Connect to Web Application

  • Open SQL Server and create database and also user table.
  • Database Name “WebAppDemo” same as our Web Application name, then click OK;
  • Database Name -> Table -> table option “WepAppDemo -> Table -> Table”
  • This is the sample table of table users; CTRL S, then name as users table. then OK
  • Here the users table in WebAppDemo database

VI. Connect SQL Server to ASP.NET Web Application

  • Add new SQL Server or connect new Server
  • Connect

VII. Add Model Entity (ADO.NET)

  • What is data entity model?
    • The Entity Data Model (EDM) is an extended version of the Entity-Relationship model which specifies the conceptual model of the data using various modelling technique. It also refers to a set of concepts that describe data structure, regardless of its stored form.
  • What is ADO.NET
    • ADO.NET is the data access component for the . NET Framework. ADO.NET leverages the power of XML to provide disconnected access to data. ADO.NET is made of a set of classes that are used for connecting to a database, providing access to relational data, XML, and application data, and retrieving results.
  • Right Click Model -> Add -> New Item
  • Under Visual C#, Click Data and choose ADO.NET Entity Data Model;
    • Name the file model as “LoginDataModel” then Click Add button.
  • Entity Data Model Wizard
    • Select EF Designer from database and Click Next;
  • Click “New Connection
    • Data Source please select Microsoft SQL Server (SQLClient).
    • Server name, Put the SQL Server name.
    • Select or Enter the Database Name, Sample “WebAppDemo
    • Click button “Test Connection“. If Connection is suceeded. Click Ok;
    • Then Click Next.
    • Please refer to photo below.
  • Choose and follow the steps.
    • Choose Entity Framework 6x;
    • Then Click Next Button.
    • Check the Table -> dbo -> users;
    • then click Finish button.
  • Here the Users table model;

VIII. Put Authentication Identity in Home Controller

  • What is Authentication Identity
    • Authentication is the process of identifying users and validating who they claim to be. One of the most common and obvious factors to authenticate identity is a password. If the user name matches the password credential, it means the identity is valid, and the system grants access to the user.
  • Home Controller
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace WebAppDemo.Controllers
{
    public class HomeController : Controller
    {
        [Authorize] // put authorize 
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }
    }
}
  • after putting {[Authorize]} this is the result, its might be user not authorize to access the default index of Home Controller.
  • To fix this, goto Web.Config
    • the add the to your Web.Config file
  • Code
 <authentication mode="Forms">
	<forms loginUrl="/Login/Index"></forms>
</authentication>
  • loginUrl=”/Login/Login”
    • the Login refer to the Login Controller, and Index refer to Index Method in Login Controller.

Now let proceed to create a Login Controller;

IX. Create Login Controller

  • Rigth click the Controller folder -> hover the Add option -> Click the Controller
3
  • Select Controller -> MVC 5 Controller – Empty -> Add
    • Name the Controller “LoginController” and click Add.
  • Login Controller;
  • Create View in your Index method in Login Controller
    • Right click the Index method in Login Controller, then Click Add View
    • Select View -> MVC 5 View -> then click Add button.
    • Add view
      • View Name as “Index”
      • Template “Create
      • Model Class “user(WebAppDemo.Models)
      • WebAppDemoEntities(WebAppDemo.Models);
      • Check Create as a Partial View
      • then Click Add Button.
  • View Code or Login
@model WebAppDemo.Models.user

@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()
    
<div class="form-horizontal">
    <h4>User Login</h4>
    <hr />
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    <div class="form-group">
        @Html.LabelFor(model => model.username, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.username, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.username, "", new { @class = "text-danger" })
        </div>
    </div>
    <div class="form-group">
        @Html.LabelFor(model => model.password, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.password, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.password, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        <label class="field-validation-error">@Html.DisplayFor(model => model.response)</label>
       
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Login" class="btn btn-default" />
        </div>
    </div>
</div>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

  • Login Controller Code
using Microsoft.AspNet.Identity;
using Microsoft.Owin.Security;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using WebAppDemo.Models;

namespace WebAppDemo.Controllers
{
    public class LoginController : Controller
    {
        // GET: Login
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Index(user loginmodel, string returnURL)
        {
            if (IsUsersValid(loginmodel))
            {
                FormsAuthentication.SetAuthCookie(loginmodel.username, false);
                Session["username"] = loginmodel.username;
                return Redirect(returnURL);
            }
            else
            {
                //loginmodel.response = "Wrong Username and Password";
                return View("Index", loginmodel);
            }
        }

        private bool IsUsersValid(user m)
        {
            using (WebAppDemoEntities1 db = new WebAppDemoEntities1())
            {
                var userret = db.users.Where(x =>x.username == m.username && x.password == m.password).FirstOrDefault();
                if (userret == null)
                {
                    //m.response = "Wrong Username and Password";
                    //return View("Index", m);
                    return false;
                }
                else
                {
                    return true;
                }
            }
                //return (m.username == "admin" && m.password == "admin");
        }

        //
        // POST: /Account/LogOff
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult LogOff()
        {
            //AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
            FormsAuthentication.SignOut();
            //Request.Cookies.Clear();
            return RedirectToAction("Index", "Home");
        }

       
    }
}
  • Login View

X. Register Controller

Also I created Register Controller, to create the Controller please back to LoginController.

  • View code Index method in Register Controller.
@model WebAppDemo.Models.user

@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()
    
    <div class="form-horizontal">
        <h4>User Registration</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.id, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.id, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.id, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.username, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.username, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.username, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.password, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.password, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.password, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.name, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.name, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.name, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.email, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.email, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.email, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

  • Register Controller Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using WebAppDemo.Models;

namespace WebAppDemo.Controllers
{
    public class RegisterController : Controller
    {
        // GET: Register
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Index(user model)
        {
            using (WebAppDemoEntities1 db = new WebAppDemoEntities1())
            {
                //var userret = db.users.Where(x => x.username == model.username && x.password == model.password).FirstOrDefault();
                db.users.Add(model);
                db.SaveChanges();

                FormsAuthentication.SetAuthCookie(model.username, false);
                Session["username"] = model.username;
                return Redirect("/home/index");
            }
            return View();
        }
    }
}
  • Register View

XI. Home Controller

This is the code of our home controlelr.

  • Home Controller Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebAppDemo.Models;

namespace WebAppDemo.Controllers
{
    public class HomeController : Controller
    {
        [Authorize] // put authorize 
        public ActionResult Index()
        {
            using (WebAppDemoEntities1 db = new WebAppDemoEntities1())
            {
                List<user> model = db.users.ToList();
                return View(model);
            }
            return View();
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }
    }
}
  • Home Index View Code
@model List<WebAppDemo.Models.user>

@{
    ViewBag.Title = "Home Page";
}

<div class="jumbotron">
    <div class="row">
        <table class="table">
            <thead>
                <tr>
                    <td>id</td>
                    <td>username</td>
                    <td>Email</td>
                    <td>name</td>
                </tr>
            </thead>
            <tbody>
                @for (int i = 0; i <= Model.Count() - 1; i++)
                {
                    <tr>
                        <td>@Model[i].id.ToString()</td>
                        <td>@Model[i].username.ToString()</td>
                        <td>@Model[i].email.ToString()</td>
                        <td>@Model[i].name.ToString()</td>
                    </tr>
                }
            </tbody>
        </table>
    </div>
</div>

  • Home View

XII. Database Model Entity

  • User Model
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated from a template.
//
//     Manual changes to this file may cause unexpected behavior in your application.
//     Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace WebAppDemo.Models
{
    using System;
    using System.Collections.Generic;
    
    public partial class user
    {
        public int id { get; set; }
        public string username { get; set; }
        public string password { get; set; }
        public string name { get; set; }
        public string email { get; set; }
    }
}

GitHub Repository

Support and follow my GitHub profile, to get the source code of this project. click GitHub Here!.

Related Topics

6 Replies to “ASP.NET Web Application (.NET Framework) – Login and Registration using SQL Server”

  1. Simply wish to say your article is as astonishing. The clarity in your submit is simply excellent and i can suppose you’re a professional in this subject.
    Fine with your permission let me to snatch your RSS feed to stay
    up to date with drawing close post. Thank you a million and please keep up the rewarding work.

  2. Heya i’m for the first time here. I came across this board and I find It truly useful & it helped me out much.
    I hope to give something back and help others like you aided me.

  3. Good ?I should certainly pronounce, impressed with your site. I had no trouble navigating through all tabs as well as related information ended up being truly easy to do to access. I recently found what I hoped for before you know it in the least. Reasonably unusual. Is likely to appreciate it for those who add forums or anything, website theme . a tones way for your client to communicate. Excellent task..

Leave a Reply to https://tworivertimes.com/en/hotmail-login/ Cancel reply

Your email address will not be published. Required fields are marked *