ASP.NET Core

Introduction to ASP.NET Core and Asp.Net Core 2.X?

Asp.Net Core is a cross platform open source framework for building modern, cloud based, Internet connected applications. With ASP.net Core you can.
  1. You can build Web App’s, Web API’s, Services, IOT apps ect..
  2. You can work ASP.NET core applications on Windows, Linux or MacOS
  3. You can deploy Cloud or on premise as well.
  4. You can run .NET Core as well as .NET Framework
Why to use Asp.net Core?
ASP.NET Core is Redesigned for  ASP.NET 4.X, with architectural changes that results in a leaner, more modular framework.
  1. Razor Pages makes coding page focused scenarios easier and more productive.
  2. Ability to develop and run on Windows, macOS and Linux.
  3. Environment based configuration.
  4. Built in dependency injection.
  5. A lightweight, high performance and modular HTTP request pipeline.
  6. Ability to host on IIL, Ngix, Apache, Docker or Self host.
Asp.Net Core Installation Guide?
ASP.Net Core > =1.0 will support VS-2015 ,Asp.net core 2.0 will support VS-2017.
If you want to download Asp.Net core, Download here. https://dotnet.microsoft.com/download. You can see Windows, linux and mocOS in the given Link.
Note: Now the latest Asp.Net core version is Asp.Net Core 3.0.

Choosing Between Asp.Net Core and Asp.Net Framework for server applications?
Asp.Net Core and Asp.Net both shares same components. However, while choosing the framework there is a fundamental difference between both.


1. Asp.Net Core Application:
  1. You Application need Cross Platform.
  2. Your application need high performance and scalable.
  3. Your application will target Micro Services. 
  4. Your application need to host in IIS, NGix, Apache and Docker container.
2. Use .Net Framework
  1. Your application is currently working on .Net framework.
  2. Your application is using third party DLL’s 
.Net framework with different platform.

.Net Framework
.Net Core
Portable Application

Latest and full-fledged framework
We can develop Web Applications, Win- 
Forms, Web API’s, WCF, lot more. But deploy only IIS,

Deployment in Windows only  
Portable or self-contained application

For Universal Windows platform and 
Asp.Net Core applications

Deployment in Windows, mac, Linux Etc...


How to Create Asp.net Core Web Application?

Open Visual Studio 2017 => File New Project=> and left side Select .NET Core and Select Asp.NET Core Web Application.
If suppose, click on Web in the given window. You will get both ASP.NET Framework and ASP.NET core application.

If you want only .NET Core application click on .NET core tab in the left side. And then select ASP.NET Core Web Application


At the Top of window you need to select Which .Net Core version you are selecting. We have Asp.NET Core 2.0, Asp.NET Core 2.1, Asp.NET Core 2.2. So the latest version is Asp.NET Core 2.2. So select latest version Asp.NET Core 2.2.



Here, I have created the Web Application with Model, View and controller. After Successful creation, We can get below view.


What is wwwroot In Asp.Net Core?
In Asp.net Core Project , wwwroot folder is treated as a web root folder. All Static files like HTMML, JavaScript, Js, Css and Images files can be stored in any of the wwwroot folder. Only those static files in the web root(wwwroot) folder can be served over in the http request. All the static files in other folder will be blocked and cannot be accessed through the http request.
In the wwwroot folder, there should be separate folders for different type of files. 


Note: For accessing the Static flies we should include middleware method in the Startup.cs class file. In ASP.NET Core 2.X by default it will provide middleware method.
app.UseStaticFiles();  
the UseStaticFiles() will be included in the Startup.cs class in the configuration.


What is Program.cs In Asp.Net Core?
In Asp.Net Core application Execution starts from public static void Main() method in the
Program.cs class file. In program class we will create Host for the web application with
IWebHostBulder.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;

namespace AspNetCore
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateWebHostBuilder(args).Build().Run();
        }
        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>();
    }
}

WebHostBuilder is used to create and configure a host to the web application.
WebHost.CreateDefaultBuilder(args). CreateDefaultBuilder() method is preconfigured
methods. That can be configured by default when calling from webHost class. When we call
CreateDefaultBuilder(), Internally it will configure to Kestral web server , IIS Integration
and other configurations.

.Usekestral() Kestral is a open source cross platform internal web server for Asp.Net Core.
It is used to be proxy.
Aps.Net Core is a open source is cross platform. So, it can used any web server not only IIS
but also Apache, Ngix etc..

.UseIISIntegration(): this method specifies IIS is the internal webserver.

.UseStartup<Startup>() this method specifies startup class to be used by the webserver. By default Startup.cs file will create in the Asp.Net Core application. Startup class is same as Global.asax file in the Asp.Net Framework. We can create and configure request pipeline in the startup class. We can rename Startup.cs class with any other name it not mandatory.

.Build() It will build the IWebHost and return which host by the web application internally.

After building the web host application, host.Run() method will start and run the web application and block calling thread until host shutdown.


Asp.Net Core application start with main method of program class and executes one by one.


What is Startup class In Asp.Net Core?

Startup class contained in the Startup.cs file in the root folder of the project. Startup class is same like Global.asax file in the .Net framework. Startup class executes first, when application starts.
Startup class will be configured using UseStartup<T>() method at the time of configuring the web host in the main method of Program class.
Here, In UseStartup<T>()  T specifies that class name startup in startup.cs. We can rename this startup.cs with other name also.

Some for the configurations in Startup.cs file is shown below.


public void ConfigureServices(IServiceCollection services) { }



This above method is gets called be the runtime. Use this method to add services to the container.

public void Configure(IApplicationBuilder app, IHostingEnvironment env) 


This above method is gets called by the runtime. Use this method to configure the http request pipe line.
In this configuration we can use MVC mapping routing, rendering static files, http redirection.   
Here we can set developing mode and production mode for debugging between development and production deployment.
app.UseStaticFiles();  
the UseStaticFiles() will be included in the Startup.cs class in the configuration. This configuration configures and access the static file from wwwroot folder

How to Create Model, View and Controller in Asp.Net Core project?

In the View Expand View, right click on Home Folder => Add=> View=> add name to the view.

Model Class:
From the project right click on the Model folder, Add UserModel.cs class file to the project. Add model properties to the UserModel class. Shown code below.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace AspDotNetCore.Models
{
    public class UserModel
    {
        public string Name { get; set; }
        public string Email { get; set; }
        public string Password { get; set; }
    }
}

Data Access Layer to the project?

For accessing the DB data to the application, I have created DataAccess layer. For data in data access layer, I have crated Interface like IUserDataAccess.cs , for implementing UserDataAccess.cs class files in the DataAccess Folder. Shown in the  code below.

IUserDataAccess interface class?

In the IUserDataAccess interface class, I have declared RegisterUser Method.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AspDotNetCore.Models;

namespace AspDotNetCore.DataAccess
{
    public interface IUserDataAccess
    {
        bool RegisterUser(UserModel user);
    }
}

Implementation in derived class?
In the UserDataAccess class, I have extended IUserDataAccess interface. In the derived class, I have implemented RegisterUser method for saving user data into the database from user input.

using System.Data;
using System.Data.SqlClient;
using AspDotNetCore.Models;


namespace AspDotNetCore.DataAccess
{
    public class UserDataAccess : IUserDataAccess
    {
        public bool RegisterUser(UserModel user)
        {
            string connectionString = "Data Source=XXXXXXX;Initial Catalog=XXXXXXX; Persist Security Info=True; User ID=XXXXXXX;Password=XXXXXXX;";
            using (SqlConnection con = new SqlConnection(connectionString))
            {
                con.Open();
                SqlCommand cmd = new SqlCommand("sp_RegisterUser", con);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.Add("Name", SqlDbType.NVarChar);
                cmd.Parameters.Add("Email", SqlDbType.NVarChar);
                cmd.Parameters.Add("Password", SqlDbType.NVarChar);
                int val = cmd.ExecuteNonQuery();
                con.Close();
                if (val > 0)
                    return true;
            }
            return false;
        }
    }
}

Dependency Injection?

Dependency is nothing but loosely coupling of objects. For configuring the Dependency injection, In the Configuration Services, I have added a scoped service of the type specified in the class Service (TService) with an implemented type specified in the class implementation (TImplementation) to the specified IServiceCollection
The Added scope in the ConfigurationService in the Startup class is shown below.
// This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
            services.AddScoped<IUserDataAccess, UserDataAccess>();
        }

Accessing Dependency Injection in the Controller?

Accessing dependency injection classes in the controller is like, By creating constructor to the controller. Is shown below.

using System;
using Microsoft.AspNetCore.Mvc;
using AspDotNetCore.Models;
using AspDotNetCore.DataAccess;

namespace AspDotNetCore.Controllers
{
    public class HomeController : Controller
    {
        public readonly IUserDataAccess _userDataAccess;
        public HomeController(IUserDataAccess userDataAccess)
        {
            _userDataAccess = userDataAccess;
        }
    }

}

Controller with Register Action?

For passing information from view to controller to Model, in the controller, I have created Register POST method in the Home controller. Shown in the code below.

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

namespace AspDotNetCore.Controllers
{
    public class HomeController : Controller
    {
        public readonly IUserDataAccess _userDataAccess;
        public HomeController(IUserDataAccess userDataAccess)
        {
            _userDataAccess = userDataAccess;
        }
        public IActionResult Index()
        {
            return View();
        }

        public IActionResult Privacy()
        {
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
       return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }

        public IActionResult Register()
        {
            return View();
        }

        [HttpPost]
        public IActionResult Register(UserModel user)
        {
            if (!string.IsNullOrEmpty(user.Email))
                _userDataAccess.RegisterUser(user);

            return View();
        }
    }
}

Register View?

Right Click on the View, Create a view and name it as Register.cshtml. In the View, I have included UserModle at the top  @model AspDotNetCore.Models.UserModel.

@model AspDotNetCore.Models.UserModel
@{
    ViewData["Title"] = "Register";
}
<div>  

    <form asp-action="/Home/Register">
        <div class="col-lg-6 p-lg-4" style="margin: 0 auto; border:1px solid #808080;">
            <div class="form-group">
                <label>Name</label>
                <input type="text" class="form-control" asp-for="Name" />
            </div>
            <div class="form-group">
                <label>Email</label>
                <input type="text" class="form-control" asp-for="Email" />
            </div>
            <div class="form-group">
                <label>Password</label>
                <input type="password" class="form-control" asp-for="Password"/>
            </div>
            <div class="form-group float-right">
                <input type="submit" class="btn btn-success btn-sm" value="Register" />
                <input type="button" class="btn btn-default btn-sm" value="Cancel" />
            </div>
            <div class="clearfix"></div>
        </div>
    </form>

</div>


Here, if we overserve the view code. I have added form with Test boxes of input type and added the Model property to asp-for.

asp-action="/Home/Register": This will call the Register action method in the Home controller when we post the data
asp-for="Email" :  This will access the email to the Email property in the UserModel class. 

Final register form view?

Run the core application this form will appear shown in below.



Popular Posts