Introduction
This article is based on the webinar I gave on 6 March 2017. Thanks to the all the people joining in and sharing the knowledge and Mumbai Techie Group for again giving me the opportunity to share my learning with all the Attendee and getting involve in the Community.
Background
I received lot of feedback after the webinar, it was mixture of all, as i call myself a learner i want to improvise on all the aspects which people told me i can improve. I was happy and enthusiastic to share my knowledge and as well patient enough to note down the learnings. So i decided i should also blog my webinar agenda where people can get the resources to get started along with brief of all the agendas which i covered in the article or due to time constraint i was not able to show them the code. I hope i will learn from my mistake and in future will prioritize to not make the same mistake twice. Thanks all for taking your time and giving me the feedback, I appreciate that a lot.
Youtube Link for the .NET CORE and ASP.NET CORE Webinar
Agenda For the Day
- Why ASP.NET 5.0 to .NET CORE 1.0
- Introduction to .NET CORE
- Command Line Tooling
- Running your first dot net core program in windows
- Running your first dot net core program in ubuntu VM
- Visual Studio Code
- Where is my ASP.NET?
- Middleware
- Sample ASP.NET Core application
- Dependency Injection in ASP.NET Core
- Deploying ASP.NET Core application using VsCode command line
Why ASP.NET 5.0 to .NET CORE 1.0
In this topic, i talked regarding the organization changes happening in Microsoft that cause the death of ASP.NET 5.0. I forget to tell that I didn’t impact the overall architecture of the.NET CORE 1.0 but it did impact the release candidate ASP.NET 5.0. Guys if you are really interested in knowing what actually happened what lead to the emergence of.NET CORE who they are actually targeting. My honest suggestion will be to watch this below mentioned the video.
-
Introduction to.NET CORE
-
Command Line Tooling
-
Running your first dot net core program in windows
-
Running your first dot net core program in ubuntu VM
-
Running your first dot net core program in ubuntu VM
-
Visual Studio Code
In order to read and learn more about above topics, I would recommend you to please read my previous articles
https://sailleshpawar.wordpress.com/2016/12/10/introduction-to-net-core/
https://sailleshpawar.wordpress.com/2017/02/20/learning-net-core-deep-down/
where I have talked about.NET CORE using VS code deep down. In case if you still face any problem or confusion feel free to ask the same on below comment section.
Where is my ASP.NET?
So, folks, I discussed that our majority of our time at the office is consumed while developing a web application, pretending all of us to be a web developer. So the main thing for career perspective is learning what ASP.NET seems like in ASP.NET Core because at the end of the day we have to create web applications.
So the main thing for career perspective is learning where ASP.NET seems like in ASP.NET Core because at the end of the day I have to create a business web application, not a console application. So, folks, in.NET CORE ASP.NET Core is a console application which will be responsible for creating its own web server as per your requirement, setting it up with all the configuration that you want to build with and then run it up once you want.
Let’s go and have Jam pack session of code to inspect the ASP.NET CORE
Here I have small scaffold CSharp program with hello world, now we gonna make our simple ASP.NET Core from the console program. So in order to create a web application, we need a web server we can run our web application. In ASP.NET Core we have a new lightweight cross-platform web server which has the capability of running cross-platform known as Kestrel. Kestrel is lightning fast web server which can server millions of request at a time and is based on the same library called Libuv which is used in Node.js
So I need to add the kestrel web server in our application and I will also use IISIntegration dependency which helps me to deploy my app on IIS once I am done creating the web application.
You all will be thinking will we have all powers of IIS…..?
My honest answer will be no, if you are targeting cross platform then we can ‘t be dependent on IIS. So now IIS will be working as a proxy server which will just pass all the request from the web to kestrel server to process.
Once we are done restoring the packages we are ready to set up our kestrel web server.
In ASP.NET Core we have a class called Startup which is a need in order to configure our web server. The Startup class gives us the power to control the web application as per our directions. Startup class consists of two methods
ConfigureServices(IServiceCollection services)
and
Configure(IApplicationBuilder app)
methods.
These two methods are the benchmark of the overall application and will decide how request flows through the pipeline. In .NET Core everything is modular and intact so we can swap anything out and swap anything in whenever we want to. We are the captain of this ship but the captain that knowledge of details as well will take good decisions. So be a good Captain as Jack Sparrow.
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
public class StartUp
{
public void ConfigureServices(IServiceCollection services)
{
//Responsible for injecting this class or service we want in our Controller
}
public void Configure(IApplicationBuilder app)
{
//Set up your http pipeline
}
}
Once we are done with done declaring ConfigureServices() and Configure
method. We will now show hello world using ASP.NET CORE. We need to add middleware (Note* we will be talking about middleware in depth later on in this blog) which will write hello to the browser for each request that comes to the web server as shown below. This sample sets up a single request delegate that handles all request and returns the string.
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Http;
public class StartUp
{
public void ConfigureServices(IServiceCollection services)
{
//Responsible for inject this class or service we want
}
public void Configure(IApplicationBuilder app)
{
app.Run(context=>{
return context.Response.WriteAsync("HELLO WORLD FROM ASP.NET CORE");
});
}
}
Now once we are done with Let’s try to continue with setting up our WebServer.
using System;
using Microsoft.AspNetCore.Hosting;
namespace ConsoleApplication
{
public class Program
{
public static void Main(string[] args)
{
var host=new WebHostBuilder()
.UseKestrel()
.UseIISIntegration()
.UseStartup()
.Build();
host.Run(); //run the server
}
}
}
In order to run our first application we just simply press F5
Middleware
So each request can subsequently have a PreProcessive logic and PostProcessive logic once the request completes and once one request one it will again flow to the middleware and then back to the UI screen. We can chain up multiple delegates using the app.Use as shown below. The next parameter represents the next delegate to be called in the pipeline.
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Http;
using System;
public class StartUp
{
public void ConfigureServices(IServiceCollection services)
{
//Responsible for inject this class or service we want
}
public void Configure(IApplicationBuilder app)
{
//middleware
app.Use(async(context,next)=>{
await context.Response.WriteAsync("I will execute first"+Environment.NewLine);
await next.Invoke();
await context.Response.WriteAsync("I will execute at last"+Environment.NewLine);
});
app.Run(context=>{
return context.Response.WriteAsync("HELLO WORLD FROM ASP.NET CORE"+Environment.NewLine);
});
}
}
Creating your own Basic Authentication Middleware of ASP.NET WEB API CORE
In order to learn asp.net web api, I would recommend you to go Learn API and be API expert and also learn what is basic authentication in web api from Basic Authentication
For this demo, I will be using visual studio and I would consider that you have some abstract knowledge of web api and basic authentication. First, create a simple ASP.NET CORE WEB API with basic ValuesController.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace WebAPI.Controllers
{
[Route("api/[controller]")]
public class ValuesController : Controller
{
// GET api/values
[HttpGet]
public IEnumerable Get()
{
return new string[] { "value1", "value2" };
}
}
}
In order to create the AuthenticationMiddleware I have created a class named Authorize where the user will be authorized to access the API based on the Authorization key passed.
It has a parameterized constructor which will take RequestDelegate which will have information which delegate to call next or invoke.
using Microsoft.AspNetCore.Http;
using System;
using System.Text;
using System.Threading.Tasks;
namespace WebAPI.Controllers
{
public class Authorize
{
int i = 0;
private readonly RequestDelegate _next;
static string strToken = "";
string strTokVal = "";
public Authorize(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext _context)
{
string authHeader = _context.Request.Headers["Authorization"];
if (!string.IsNullOrEmpty(authHeader))
{
string authStr = _context.Request.Headers["Authorization"];
authStr = authStr.Trim();
if (authStr.IndexOf("Basic", 0) != 0 || string.IsNullOrEmpty(authStr))
{
DenyAccess(_context);
return;
}
authStr = authStr.Trim();
string encodedCredentials = authStr.Substring(5);
byte[] decodedBytes;
decodedBytes = Convert.FromBase64String(encodedCredentials);
string s = new ASCIIEncoding().GetString(decodedBytes);
string[] userPass = s.Split(new char[] { ':' });
string username = userPass[0];
string password = userPass[1];
if (!(string.IsNullOrEmpty(username) && string.IsNullOrEmpty(password)))
{
if (username == "Saillesh" && password == "Saillesh@123")
{
AllowAccess(_context);
}
else
{
DenyAccess(_context);
return;
}
}
else
{
DenyAccess(_context);
return;
}
}
else
{
_context.Response.StatusCode = 401;
_context.Response.Headers.Add("WWW-Authenticate", "Basic Authentication");
}
}
private void DenyAccess(HttpContext app)
{
app.Response.StatusCode = 401;
app.Response.WriteAsync("401 Access Denied");
return;
}
private async void AllowAccess(HttpContext app)
{
app.Response.StatusCode = 200;
await _next(app);
}
}
}
I would not recommend this authentication for public API this authentication can be used where you have an application which accesses the web server which can be of Java or WebAPI with the token and the API is calling inhouse another api like this just to check whether the request came from the authentic source. The UserName and Password are magic numbers which can be checked at the db level. UserName and Password are passed using 64 encoding which can be easily encoded or decoded using ENCODE/DECODE TO BASE 64
So once the request will come from the UI and we will enforce the request to go through authentication middleware by calling the invoke method based on the credential passed user will be denied or allowed access to the API. If user passed the wrong credentials 401: UnAuthorized status code message will be sent.
await _next(app);
await _next(app); will call the next MVC middleware and get the response from the web api.
Once we are done with our Class let register it as Middleware in order to register the class as Middleware I will create another class which will be static class AuthorizationMiddleware
using Microsoft.AspNetCore.Builder;
using WebAPI.Controllers;
namespace WebAPI.Middleware
{
public static class AuthorizationMiddleware
{
public static void UseAuthorizationMiddleware(this IApplicationBuilder builder)
{
builder.UseMiddleware();
}
}
}
Setting Up the Pipeline
Now I want all the request to be refined by AuthorizationMiddleware so I will set up my pipeline in Configure method and add this to the top of all middlewares.
public void Configure(IApplicationBuilder app)
{
app.UseAuthorizationMiddleware();
app.UseMvc();
}

Calling API Using Postman
Sample ASP.NET Core application

namespace MarchDemo.Model
{
public class Attendee
{
public int Id { get; set; }
public string Name { get; set; }
public string Profession { get; set; }
public string MobileNumber { get; set; }
public string EmailId { get; set; }
}
}
Views
Controllers
using System; using System.Linq; using MarchDemo.Model; using MarchDemo.Persistence; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; namespace MarchDemo.Controllers { public class AttendeeController : Controller { private ApplicationDbContext _context; public IActionResult Index() { return View(); } public IActionResult AllAttendees() { _context=new ApplicationDbContext(); return View("AllAttendees",_context.Attendees.ToList()); } public IActionResult AddAttendee(Attendee attendee) { _context=new ApplicationDbContext(); _context.Attendees.Add(attendee); _context.SaveChanges(); return RedirectToAction("AllAttendees"); } } }
EF Mapping
using MarchDemo.Model; using Microsoft.EntityFrameworkCore; namespace MarchDemo.Persistence { public class ApplicationDbContext:DbContext { public DbSet Attendees {get;set;} protected override void OnConfiguring(DbContextOptionsBuilder options) { options.UseSqlServer(@"Data Source=.;Initial Catalog=MumbaiTechieGroup;Integrated Security=True"); } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity().ToTable("MtgParticipants"); } } }

using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.DependencyInjection; using Microsoft.AspNetCore.Http; using System; public class StartUp { public void ConfigureServices(IServiceCollection services) { services.AddMvc(); } public void Configure(IApplicationBuilder app) { app.UseStaticFiles(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Attendee}/{action=Index}/{id?}"); }); } }
Add one more dependency for enable the application to load Views…
"Microsoft.AspNetCore.StaticFiles": "1.1.0",
Now, lets run our first basic ASP.NET CORE WEB APPLICATION which will store the Attendee details to the database and show the same in another page.
Dependency Injection in ASP.NET Core
Dependency Injection is a technique which helps us to inject dependent objects of a class. In order to learn the basic of Dependency i would recommend you to watch the video of shiv prasad Koirala sir on Dependency Injection
Let start with Dependency Injection in ASP.NET Core. ASP.NET Core provide us with build in Dependency Injection framework which was lacking in the previous version of MVC you can still use third party tool like NInject, AutoFac, Unity etc to do the same.
ASP.NET CORE provide us three type of Injections
- AddSingleton
- AddTransient
- AddScoped
AddSingleton
When we use AddSingleton type the framework will create the single instance of the object of a class threw out the lifetime of the application.
AddTransient
AddTransient will create the new instance each time the request comes to the web application.
AddScoped
I found this to be extremely difficult to convey this DI but defining it I would say it will return the same of the for the class referred in i.e. a class referred in Service class or repository etc. We will see this in the demo.
I hope you have read the blog and download the source code from the Github and I am sure all your doubts who have been cleared as off now. If not feel free to reach me.
Deploying ASP.NET Core application using VsCode command line
The asp.net core is cloud ready framework which can be deployed cross platform. So in this context, we will be deploying the same to IIS. You might be thinking that will we be able to use the blown power of IIS, then my honest answer will be no. IIS with ASP.NET CORE work as a proxy server whose role is to pass all the HTTP request to kestrel. As Microsoft team has said that kestrel not being matured enough should be used behind the IIS. So let’s publish our ASP.NET Core application to IIS.


So now in order to deploy the application on IIS. We need to add the new application to the default website as shown below:.