Friday 2 October 2020

Asp.net core Registration, Login, Logout example without using identity

 In this tutorial you will learn how to create login and registration form using asp.net core with real-time example. And also how to use session  asp.net  core. We used the "Dotnet core database first approach" for crud operation.

We have asp.net core identity login,logout example also in our next tutorial.

asp.net core login logout registration example

 

Verify the below-mentioned software, framework and tools are available on your system

·         Visual studio 2017

·         Core 2.0

·         Sql server

Create user details table in sql server database.

CREATE TABLE [dbo].[userdetails](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[Name] [VARCHAR](50) NULL,
	[Email] [VARCHAR](50) NULL,
	[Password] [VARCHAR](50) NULL,
	[Mobile] [VARCHAR](50) NULL,
PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

2. Create new asp.net core mvc project in visual studio in the name of Dbfirstapp.

 

3. Create the class for ecommerceContext.cs, Userdetails.cs, LoginViewModel.cs, RegistrationViewModel.cs in Model  folder.

Userdetails.cs: This class contains all the table column properties.

using System;
using System.Collections.Generic;
 
namespace Dbfirstapp.Models
{
    public partial class Userdetails
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Email { get; set; }
        public string Password { get; set; }
        public string Mobile { get; set; }
    }
}

LoginViewModel.cs: This class created for login screen properties and validation.

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
 
namespace Dbfirstapp.Models
{
    public class LoginViewModel
    {
        [Required]
        public string Email { get; set; }
 
        [Required]
        [StringLength(10, MinimumLength = 6)]
        public string Password { get; set; }
    }
}

RegistrationViewModel.cs : This class created for registration screen properties and validation.

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;
 
namespace Dbfirstapp.Models
{
    public class RegistrationViewModel
    {
        [Required]
        [StringLength(15, MinimumLength = 3)]
        //[StringLength(15, ErrorMessage = "Name length can't be more than 15.")]
        public string Name { get; set; }
        [Required]
        [RegularExpression(@"^(\d{10})$", ErrorMessage = "Mobile no not valid")]
        public string Mobile { get; set; }
        [Required]
        [EmailAddress]
        public string Email { get; set; }
 
        [Required]
        [StringLength(10, MinimumLength = 6)]
        public string Password { get; set; }
        [Required]
        [NotMapped] // Does not effect with your database
        [Compare("Password")]
        public string ConfirmPassword { get; set; }
 
    }
}
 

I have explained how to achieve model validation in asp.net core my next tutorial. If you are not aware of that go through that tutorial. 

ecommerceContext.cs : This is our Dbcontext file for achieving database first approach entity framework.

using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;
 
namespace Dbfirstapp.Models
{
    public partial class ecommerceContext : DbContext
    {
        public virtual DbSet<Userdetails> Userdetails { get; set; }
 
        public ecommerceContext(DbContextOptions<ecommerceContext> options):base(options)
        {
 
        }
 
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Userdetails>(entity =>
            {
                entity.ToTable("userdetails");
 
                entity.Property(e => e.Email)
                    .HasMaxLength(50)
                    .IsUnicode(false);
 
                entity.Property(e => e.Mobile)
                    .HasMaxLength(50)
                    .IsUnicode(false);
 
                entity.Property(e => e.Name)
                    .HasMaxLength(50)
                    .IsUnicode(false);
 
                entity.Property(e => e.Password)
                    .HasMaxLength(50)
                    .IsUnicode(false);
            });
        }
    }
}
 

4. Configure connection string in appsetting.json file

{
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "ConnectionStrings": {
    "DevConnection": "Server=(local)\\SQLEXPRESS01;Database=ecommerce;Trusted_Connection=True;MultipleActiveResultSets=True;"
  }
}

5. Add Dbcontext service, Session in a startup.cs file configure service function.

Use session in configure function like a below-attached screen. Remember to add code in sequence.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Dbfirstapp.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Authentication.Cookies;
 
 
namespace Dbfirstapp
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }
 
        public IConfiguration Configuration { get; }
 
 
        public void ConfigureServices(IServiceCollection services)
        {
 
            services.AddMvc();
            services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
 
            services.AddSession();
 
            services.AddSession(options => {
                options.IdleTimeout = TimeSpan.FromMinutes(30);
            });
            services.AddDbContext<ecommerceContext>(options =>
           options.UseSqlServer(Configuration.GetConnectionString("DevConnection")));
        }
 
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseBrowserLink();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }
            app.UseCookiePolicy();
            app.UseStaticFiles();
            app.UseSession();
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}
 

6. Create controller for AccountController, HomeController in controller folder.

AccountController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Dbfirstapp.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Http;
using System.Diagnostics;
 
namespace Dbfirstapp.Controllers
{
    public class AccountController : Controller
    {
        private readonly ecommerceContext _context;
 
        public AccountController(ecommerceContext context)
        {
            _context = context;
        }
 
        public IActionResult Index()
        {
            return View();
        }
        [HttpPost]
        public async Task<ActionResult> Login(LoginViewModel model)
        {
            if (ModelState.IsValid)
            {
                var userdetails = await _context.Userdetails
                .SingleOrDefaultAsync(m => m.Email == model.Email && m.Password ==model.Password);
                if (userdetails == null)
                {
                    ModelState.AddModelError("Password", "Invalid login attempt.");
                    return View("Index");
                }
                HttpContext.Session.SetString("userId", userdetails.Name);
 
            }
            else
            {
                return View("Index");
            }
            return RedirectToAction("Index", "Home");
        }
        [HttpPost]
        public async Task<ActionResult> Registar(RegistrationViewModel model)
        {
 
            if (ModelState.IsValid)
            {
                Userdetails user = new Userdetails
                {
                    Name=model.Name,
                    Email=model.Email,
                    Password=model.Password,
                    Mobile=model.Mobile
 
                };
                _context.Add(user);
                await _context.SaveChangesAsync();
 
            }
            else
            {
                return View("Registration");
            }
            return RedirectToAction("Index", "Account");
        }
        // registration Page load
        public IActionResult Registration()
        {
            ViewData["Message"] = "Registration Page";
 
            return View();
        }
 
        public  IActionResult Logout()
        {
            HttpContext.Session.Clear();
            return View("Index");
        }
        public void ValidationMessage(string key, string alert, string value)
        {
            try
            {
                TempData.Remove(key);
                TempData.Add(key, value);
                TempData.Add("alertType", alert);
            }
            catch
            {
                Debug.WriteLine("TempDataMessage Error");
            }
 
        }
    }
}

HomeController.cs

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Dbfirstapp.Models;

namespace Dbfirstapp.Controllers
{
    public class HomeController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }

        public IActionResult About()
        {
            ViewData["Message"] = "Your application description page.";

            return View();
        }

        public IActionResult Contact()
        {
            ViewData["Message"] = "Your contact page.";

            return View();
        }

        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }
}

 

7. This time to create UI(view) for login and registration. Right click the AccountController index function

and create view for login, registration function for registration view. Remember that in this function homecontroller

by default the system created when we created the project.Ignore userdetails controller in this screen,crud application purpose we created.

 

Views/Account/Index.cshtml

 

@model LoginViewModel
@{
    ViewData["Title"] = "Index";
}
 
 
<h2 class="text-center">Login</h2>
<div class="row">
    <div class="col-md-6 col-md-offset-3">
        <div class="jumbotron">
            <form role="form" asp-action="Login" asp-controller="Account" method="post">
                <div class="form-group">
                    <label for="Email">User Name</label>
                    <input type="email" name="Email" asp-for="Email" autocomplete="off" class="form-control input-sm" placeholder="Email Address">
                    <span asp-validation-for="Email" class="text-danger"></span>
                </div>
                <div class="form-group">
                    <label for="Password">Password</label>
                    <input type="password" name="Password" asp-for="Password" autocomplete="off" class="form-control input-sm" placeholder="Password">
                    <span asp-validation-for="Password" class="text-danger"></span>
                </div>
                <input type="submit" value="Login" class="btn btn-info btn-block">
            </form>
        </div>
    </div>
 
</div>

Views/Account/Registration.cshtml

@model RegistrationViewModel
@{
    ViewData["Title"] = "Register";
}

<div class="row">
    @if (TempData["validationmessage"] != null)
    {
        string alertType = "alert alert-" + TempData["alertType"];
        <div class="@alertType">
            <strong>Alert!</strong> @TempData["validationmessage"]
        </div>
    }
</div>
<h2 class="text-center">Registar</h2>
<div class="row">
    <div class="col-md-6 col-md-offset-3">
        <div class="jumbotron">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <form role="form" asp-action="Registar" asp-controller="Account" method="post">
               
                <div class="form-group">
                    <label for="Name">User Name</label>
                    <input type="text" name="Name" asp-for="Name" class="form-control input-sm" autocomplete="off" data-val="true" data-val-required="The Mobile field is required."  placeholder="Name">
                    <span asp-validation-for="Name" class="text-danger"></span>
                </div>
                <div class="form-group">
                    <label asp-for="Mobile"></label>
                    <input type="text" name="Mobile" data-val="true" autocomplete="off" data-val-required="The Mobile field is required." asp-for="Mobile" class="form-control input-sm" placeholder="Mobile">
                    <span asp-validation-for="Mobile" class="text-danger"></span>
                </div>
                <div class="form-group">
                    <label for="Email">Email</label>
                    <input type="email" name="Email" asp-for="Email" autocomplete="off" data-val="true" class="form-control input-sm" data-val-required="The Mobile field is required." placeholder="Email Address">
                    <span asp-validation-for="Email" class="text-danger"></span>
                </div>
                <div class="form-group">
                    <label for="Password">Password</label>
                    <input type="password" name="Password" asp-for="Password" autocomplete="off"  class="form-control input-sm" data-val="true" data-val-required="The Mobile field is required." placeholder="Password">
                    <span asp-validation-for="Password" class="text-danger"></span>
                </div>
                <div class="form-group">
                    <label for="ConfirmPassword">Password</label>
                    <input type="password" name="ConfirmPassword" asp-for="ConfirmPassword" autocomplete="off" class="form-control input-sm" placeholder="ConfirmPassword">
                    <span asp-validation-for="ConfirmPassword" class="text-danger"></span>
                </div>

                <input type="submit" value="Register" class="btn btn-info btn-block">
                <input name="__RequestVerificationToken" type="hidden" value="<removed for brevity>">
            </form>
        </div>
    </div>

</div>

Layout.cshtml
@using Microsoft.AspNetCore.Http
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>@ViewData["Title"] - Dbfirstapp</title>

    <environment include="Development">
        <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.css" />
        <link rel="stylesheet" href="~/css/site.css" />
    </environment>
    <environment exclude="Development">
        <link rel="stylesheet" href="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.7/css/bootstrap.min.css"
              asp-fallback-href="~/lib/bootstrap/dist/css/bootstrap.min.css"
              asp-fallback-test-class="sr-only" asp-fallback-test-property="position" asp-fallback-test-value="absolute" />
        <link rel="stylesheet" href="~/css/site.min.css" asp-append-version="true" />
    </environment>
</head>
<body>
    @{

        var userId = Context.Session.GetString("userId");
        if(userId == null)
        {
           // Context.Response.Redirect("/Account");

        }
    }
    <nav class="navbar navbar-inverse navbar-fixed-top">
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                    <span class="sr-only">Toggle navigation</span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                <a asp-area="" asp-controller="Home" asp-action="Index" class="navbar-brand">Dbfirstapp</a>
            </div>
            <div class="navbar-collapse collapse">
                <ul class="nav navbar-nav">
                    <li><a asp-area="" asp-controller="Home" asp-action="Index">Home</a></li>
                    <li><a asp-area="" asp-controller="Home" asp-action="About">About</a></li>
                    <li><a asp-area="" asp-controller="Home" asp-action="Contact">Contact</a></li>



                </ul>
                <ul class="nav navbar-nav navbar-right">
                    @if (@userId != null)
                    {
                        <li class="dropdown">
                            <a href="#" class="dropdown-toggle" data-toggle="dropdown">
                                <span class="glyphicon glyphicon-user"></span>
                                <strong>@userId</strong>
                                <span class="glyphicon glyphicon-chevron-down"></span>
                            </a>
                            <ul class="dropdown-menu">
                                <li><a asp-area="" asp-controller="Userdetails" asp-action="index"><span class="glyphicon glyphicon-log-in"></span> My Profile</a></li>
                                <li><a asp-area="" asp-controller="Account" asp-action="Logout"><span class="glyphicon glyphicon-log-in"></span>Logout</a></li>
                            </ul>
                        </li>
                            @*<li><a asp-area="" asp-controller="Account" asp-action="index"><span class="glyphicon glyphicon-user"></span> @userId</a></li>*@
                    }
                    else
                    {
                        <li><a asp-area="" asp-controller="Account" asp-action="index"><span class="glyphicon glyphicon-log-in"></span> Login</a></li>
                                <li><a asp-area="" asp-controller="Account" asp-action="Registration"><span class="glyphicon glyphicon-log-in"></span> Register</a></li>

                    }

                </ul>
            </div>
        </div>
    </nav>
    <div class="container body-content">
        @RenderBody()
        <hr />
        <footer>
            <p>&copy; 2019 - Dbfirstapp</p>
        </footer>
    </div>

    <environment include="Development">
        <script src="~/lib/jquery/dist/jquery.js"></script>
        <script src="~/lib/bootstrap/dist/js/bootstrap.js"></script>
        <script src="~/js/site.js" asp-append-version="true"></script>
    </environment>
    <environment exclude="Development">
        <script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-2.2.0.min.js"
                asp-fallback-src="~/lib/jquery/dist/jquery.min.js"
                asp-fallback-test="window.jQuery"
                crossorigin="anonymous"
                integrity="sha384-K+ctZQ+LL8q6tP7I94W+qzQsfRV2a+AfHIi9k8z8l9ggpc8X+Ytst4yBo/hH+8Fk">
        </script>
        <script src="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.7/bootstrap.min.js"
                asp-fallback-src="~/lib/bootstrap/dist/js/bootstrap.min.js"
                asp-fallback-test="window.jQuery && window.jQuery.fn && window.jQuery.fn.modal"
                crossorigin="anonymous"
                integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa">
        </script>
        <script src="~/js/site.min.js" asp-append-version="true"></script>
    </environment>

    @RenderSection("Scrip

No comments:

Post a Comment