ASP.NET Core Tutorial for Beginners

By | February 17, 2017

With this article today, we are going to start a tutorial Series on ASP.NET Core for developers having knowledge of existing Microsoft web technologies (including ASP.NET Web Forms, ASP.NET MVC, ASP.NET Web API etc.) but wanted to start the new ASP.NET Core from the very beginning. For a practical example, you can follow ASP.NET Core and Angular from scratch. Here we will start with basic core concepts and further add more practical articles to this ASP.NET Core Tutorial Series.

You can also find ASP.NET Core Web API Tutorial Series covering:

ASP.NET Core Tutorial – Start as a Beginner

ASP.NET Core 1.0 or ASP.NET 5 – MVC6 is a re-write version of ASP.NET 4.6 with following key features:

  • ASP.NET Core is Open-Source.
  • It’s a framework that is Cross-platform, means can run on Linux or MacOS. Before that .NET Framework (as a whole) can only be used in Windows platform. This is considered as a huge enhancement.
  • Ideal for building Web applications, Iot apps and mobile backends.
  • Cloud ready configuration.
  • ASP.NET Core 1.0 is smaller in size as compared to ASP.NET 4.6 framework as it runs on stripped down version of .NET Framework i.e. .NET Core 1.0.ASP.NET CORE Tutorial

At a broader view, we must be clear that:

  • ASP.NET 5 is now renamed as ASP.NET Core 1.0
  • .NET Framework 5 will be known as .NET Core 1.0 and
  • Entity Framework 7 will be renamed to Entity Framework Core 1.0.

.NET Core Vs .NET Framework

.NET Core shared a number of API with traditional .NET Framework as depicted in the following figure:.NET Core Vs .NET Framework

The difference between .NET core and .NET Framework:

.NET Core .NET Framework
Suitable for application
  • Require supporting cross-platform.
  • Require supporting microservices.
  • Require to support using Docker containers.
  • Require to provide high-performance and scalable systems.
  • Require to support side-by-side .NET versions per application.
  • Uses .NET Framework (recommendation is to extend instead of migrating).
  • Developed based on  third-party .NET libraries or NuGet packages not available for .NET Core.
  • Developed based on  .NET technologies that aren’t available for .NET Core.
  • Developed based on  a platform that doesn’t support .NET Core.
Microservices Supports microservices Does not support microservices
Docker Container Supports deployment in docker container. Does not supports deployment in docker container.
Community & learning Curve This is a new technology; therefore, the community is still growing and smaller than the community for .NET Framework. As a result, the learning curve is very big, and it takes longer time. For a comparatively older technologies, the community is big and the learning curve is small.
Deployment Deployment is easier than traditional way Deployment is time consuming

The architecture for Microsoft ecosystem can be described as following diagram:

Microsoft Ecosystem

Reference – Microsoft Docs

The main difference between .NET core and .NET framework is that new .NET core supports cross platform, therefore .NET core is the future technology.

Key Features of ASP.NET 5 or ASP.NET Core 1.0:

Key Features of ASP.NET Core

Cross Platform Support:

.NET Core is Cross-platform web framework, that is more modular and cloud optimized, can be Build and Run on Windows, Mac, Linux for modular development stack.  The libraries are modular and distributed via NuGet packages. It was architected to support an optimized development framework for web application that are deployed to the cloud. Its libraries are standard that minimizes allocations and the overall memory of our system.

Open Source:

ASP.NET Core is fully open source, developed with the community and with Microsoft’s support. Not only the source code but documentation is open source available in github and docs.asp.net respectively. We developers can download, inspect, modify and enhance it. Whatever the good work we do as a ASP.NET Core community member, we can forward it to Microsoft for approval.

Performance:

Performance has always been an issue for Microsoft .NET and to overcome this issue they introduced new managed web server i.e. “Kestrel” with .NET Core. This new Web Server written in C# is designed from scratch to be the fastest available .NET Server.

Microsoft is very successful in achieving it’s goal with respect to performance as ASP.NET Core now lands among the top in the list. Below is a comparison of ASP.NET Core with other technologies:ASP.NET Core Performance

https://twitter.com/davidfowl/status/700139258279899137

Built-In Dependency Injection:

Dependency Injection is a technique used normally to achieve loose coupling between objects and their dependencies. Using DI, an object can be used with other services without having much details about it. Dependency Injection is now built-in with ASP.NET Core framework as a Dependency Injection service container with minimal features.

Single/Unified Programming Model for MVC and Web API:

Microsoft has unified ASP.NET MVC and Web API into single programming Framework, removing the overlap between these different frameworks. Unified Framework simplifies the development process by introducing a unique namespace i.e. Microsoft.AspNet.Mvc. Also making integration easier with client-side frameworks like Grunt/Bower and simplifies adding cross-cutting concerns with controller.Unified MVC and Web API

Modularity:

While working with large-scale projects, it’s mostly difficult to maintain code as project grows. So, package based development helps maintain and update projects easier. NuGet package is now the default standard for adding new functionality to ASP.NET Core applications, that includes adding frameworks, libraries and even core features of ASP.NET.

Project.json:

The Project.json file is used for .NET Core projects to define project metadata, compilation information, and dependencies.

Followings are some of the important properties of Project.json:

Name Description Example
 name It is the name of the package, used in the assembly name. The data type name is string.  { “name”: “WebDevDemo” }
 version The data  type version is string. It is used for the NuGet package.  { “version”: “1.0.0-*” }
description It is used in the assembly to a longer description of the project. { “description”: “A Demo for my ASP.NET Core Project”}
copyright It is also used in the assembly properties , used to copyright information on project. { “copyright” : “WebDevTutorial 2017”  }
title It is not allowed when using name property. It gives the heading of the project. { “title” : “My Library” }
entryPoint The entrypoint method for the project. Main by default. { “entryPoint” : “ADifferentMethod” }
testRunner The test Runner is NUnit or xUnit . The data type of the testRunner is string. {“testRunner”: “NUnit”}
authors Data type of the authors is string [] . Authors is the array of strings of the project . {“authors”: [“Muhammad Ahmad”]}

Appsettings.json:

With ASP.NET Core, web.config is replace with Appsettings.json file for keeping all settings including connection strings, custom application settings, logging etc. Also the format is JSON instead of XML now.

Previously, we were keeping settings in web.config in XML format as:

Now, following JSON in Appsettings.json will replace the above:

Startup.cs:

Startup.cs in ASP.NET Core is basically a replacement for Global.asax in ASP.NET. Every ASP.NET Core Application requires a Startup class but it can be different for different environments. Appropriate startup.cs with respect to the environment is selected at runtime.Startup.cs in ASP.NET Core

Once the application get started, it calls the following methods as:

  • Optional ConfigureServices method to add framework services.
  • Compulsory Configure method to add the services to the container.

Have a look into complete Startup.cs as below:

Grunt, Gulp and Bower:

Grunt and Gulp are JavaScript Task Runner while Bower is web Package Manager.

Grunt:

  • Grunt is a JavaScript Task Runner.
  • It is used to automate common tasks like Bundling and Minification of JavaScript and CSS files.
  • We can use Node Project Manager(NPM)  to install Grunt as follows:
  • We can configure with ASP.NET Core with name Gruntfile.js that shouldn’t be changed.

Gulp:

  • Gulp is also a JavaScript Task Runner.
  • The Operations has to be defined in a file named Gulpfile.js.
  • It is no longer the default choice for ASP.NET Core application as it’s replaced by BuilderMinifier.
  • Gulp has to be installed globally as well as using the following command:

Bower:

  • Bower is used to manage front-end packages in a ASP.NET Core application.
  • Bower has to be installed using following command:

MVC Tag Helpers:

Tag Helpers is a way of extending functionality of HTML in Razor View engine. With tag helpers, different functionalities are added in Razor which makes development easier. It’s not only the syntax change but it really makes the Razor forms more readable.

Consider the below simple link using HTML Helper as:

The output HTML produced by above will be:

Now, we can achieve the same with Tag Helpers as follows:

If we compare syntax of both HTML Helper to Tag Helper, it’s undoubtedly more readable for developers as well as web designers or front-end developers (as they don’t need to understand C#).

More practical examples of using Tag Helpers instead of HTML Helpers are:

Simplified Tag Helper syntax will be:

Further you can find good details about MVC Tag Helpers by Dave Callan here.

ASP.NET Core Initialization Process

ASP.NET Core Initialization Process

  • The Startup.cs class provides an entry point for the application.
  • It is possible to define separate Startup classes for different environments
  • The Startup class constructor accept dependencies injected using dependency injection.
  • The Startup class is called by through invoking Startup() method in the Main method of the application which is the Program.Main(). This method is also responsible configuring services for the application are specified.
  • Startup() method also initialized the application. When the Startup class is initialized, the application’s settings are fetched from appsettings by the ConfigurationBuilder.
  • Once the ConfigurationBuilder builds all configuration. the ConfigureServices() method is invoked allowing services to be resolved from the dependency injection container and created before configuration takes place.
    • The ConfigureServices() method add services to the application’s service container.
  • Next the Configure() method is invoked. Here application settings are applied, and middleware components are registered in the application request handler pipeline.
    • The Configure() method is used to specify how the ASP.NET application will respond to individual HTTP requests in the form of middleware.
    • Middleware in ASP.NET Core are built from extension methods on IApplicationBuilder and give developers direct access to HTTP requests. Typical Use*Action* middleware will handle requests and responses and pass the request on to the next component in the pipeline for further action. In addition, Run and Map middleware delegates are used for less common scenarios – these delegates will terminate or branch the request pipeline.
    • Additional services like IHostingEnvironment and ILoggerFactory may also be configured, these services are initialized in the ConfigureServices method
Pro ASP.NET Core 1.1 MVCPro ASP.NET Core 1.1 MVC
Dive into the world of ASP.NET Core and learn how to build easy-to-maintain web applications with the MVC design pattern and ASP.NET Core.
Build a Real-world App with ASP.NET Core and Angular 2 (4+)Build a Real-world App with ASP.NET Core and Angular 2 (4+)
ASP.NET Core and Angular 2(4+) is an ideal combination for building real world modular and cloud-optimized applications.

Entity Framework in Depth: The Complete Guide
Entity Framework in Depth: The Complete Guide
Connect your applications to a SQL Server database. Understand the differences between code-first and database-first workflows….
Comprehensive ASP.NET MVC
Comprehensive ASP.NET MVC
From zero knowledge of ASP.NET to deploying a complete project to production.

New Configuration Model in ASP.NET Core 1.x. How new configuration is different from traditional way of configuration?

Let’s continue in this ASP.NET Core Tutorial about new configuration model and how it’s different from previous traditional Model?

Traditional way of configuration:

The configuration is setup in the web.config file inside the appsettings node as following:

New Configuration in ASP.NET Core:

There are different configuration provider as following:

  • File formats – configutation can be listed in INI, JSON, or XML file
    For example, here is a json file where user can defined settings configutation key of any valid format for json document, e.g. string, array, object, date and so on.
    In order to access the json file for
    The json file should follow the following naming convention

    • json
    • appsetting.<EnvironmentName>.json
  • Command-line arguments
    The following class is an example of using command line configuration:
    Arguments for command line configuration

    For command line argument, arguments must conform to one of two formats depicted in the following table. Although, the value can be null.

    Argument Format Example
    a key-value pair separated by an equals sign (=) key=value
    a key-value pair separated by a space /key value
    The key may have a prefix e.g -key2=value2, –key3=value3, /key4=value4
  • Environment variables
    In ASP.NET core application, it is also possible to add environment variable
    There are other ways to configure as following

    • In-memory .NET objects
    • An encrypted user store
    • Azure Key Vault
    • Custom providers, installed or created by user.

What is ASP.NET Core Middleware? Explain app.Use Vs app.Run in ASP.NET Core middleware?

ASP.NET Core Middleware is a function of a set of logic that can be executed in order to handle and request and corresponding response. In order to flow different intermediate operation in order to perform a  request, middle wares are used.ASP.NET Core Middleware Tutorial

Here in this above figure, there are 4 different middleware. Once the request is received by the first middleware, it executed some logic and that business logic decides whether to pass the result to the next middleware or component. If the logical operation indicates to pass forward the result to the next middleware, it pass the result to next component or middleware in the flow, and the flow goes on until the final middleware (middleware-iv) in the flow is reached. Once the final middleware in the flow completes the operation on the request, it return the result to the previous middleware (middleware-iii)  and the received result is again processed with more logic by the middleware that receives the result, although it is optional to reprocess the request, and return the result to previous middleware (middleware-ii). This process oes on until the first middleware in the flow received the resulted response, it can either return the response directly to the client, otherwise if necessary , it can re-process the returned the response and the  return the response to the client.

As Microsoft described the main responsibilities of middle-ware are as following

  • Perform business logic to process the request and decide whether to pass the result to the next middleware or component in the pipeline/flow or not.
  • Perform logical operation before and after the next component in the pipeline is invoked.

The built-in middle-ware are as following:

Middleware Description
Authentication Provides authentication support.
CORS Configures Cross-Origin Resource Sharing.
Response Caching Provides support for caching responses.
Response Compression Provides support for compressing responses.
Routing Defines and constrains request routes.
Session Provides support for managing user sessions.
Static Files Provides support for serving static files and directory browsing.
URL Re-writing Middleware Provides support for rewriting URLs and redirecting requests.

app.Use Vs app.Run

app.Use:

This is most popular building block for a middleware chain pipeline. It is used to executed operation both before and  after the request is passed to the next middleware in the pipeline. At the same time, it can short-circuit the request and force to return a result as response instead of passing the request to the next component in the pipeline.

app.Run:

app.Run execute the operation and terminates the pipeline instead of forwarding it to the next component. Usually if any request can be served by using only one middleware app.Run is used. app.Run is also used at the final middleware of the pipeline to terminate the pipeline.

Usually app.use and app.run is used together to build the pipeline:

Some notes on using Middleware:

  1. Do not call next.Invoke after calling a write method. A middleware component either produces a response or calls next.Invoke, but not both.
  2. Do not call next.Invoke after the response has been sent to the client. Changes to HttpResponse after the response has started will throw an exception. For example, changes such as setting headers, status code, etc, will throw an exception. Writing to the response body after calling next.

Routing in ASP.NET Core

In order to describe the routing life cycle we have to understand the different component used in a complete routing and their interaction among each other. In this section we would discuss

  • what is routing in a brief,
  • what are the components used in a simple routing operation
  • the different ways of build routing

What is Routing in ASP.NET Core?

In an ASP.NET application, the main functionality of routing operation is to map any incoming request to a routing handler. In order to do that route needs to be configured when the application starts.

Each route has some additional feature rather than following the request flow, for example, it can read parameter or information from URL which can be used by controller in order to process the request.

Routing operation can also be used for generating URL and mapped those generated URL to route handlers.

In a summary, the key functionality of routing operation is to:

  • map any incoming request to a routing handler
  • find a route handler based on the URL or the information provided in the URL
  • generate URLs used in response

The process of finding a route handler based on the URL or the information provided in the URL is as following:

Each app has a single collection of routes. When a request comes in, it finds the matched route with the URL by calling RouteAsync method for each route in the route collection of the app. If any one of these routes matched, it will be associated with the incoming request.

Routing is also connected to middle-ware pipeline through RouterMiddleware class.

What are the components used in a simple routing operation?

The basic components used in routing are as following

  • RouteCollection of the app
  • RouterMiddleware
  • Controller

Different ways to build routing:

There are different stage of the routing life cycle as following:

  • URL Matching
  • URL generation
  • Creating route

In the following diagram the basic of building route has been described.ASP.NET Core Routing Tutorial

URL Matching

The very first stage of the routing life cycle is the URL matching. The workflow is as following:

  • Incoming request enters to RouteMiddleware as in the above diagram.
  • RouteMiddleware invoke the RouteAsync method of each route in the RouteCollection in sequence. Where the IRouter method decides whether to handle the request or stops the processing.
  • If IRouter method set up RouteContext.Handler to a, the handler is invoked and process the request. However, if no non-null RequestDelegate is found, the middleware calls next and the request is passed to next middleware.

URL Generation

If the routing can create a URL from the information passed with the URL, URL generation takes place. For URL generation the GetVirtualPath  method of IRouter is used. This method is called for each route in the RouteCollection in sequence until the method for any route returns null.

The returned VirtualPathData object has a property called VirtualPath which is the virtual path produced by the route. This also has the Router and DataTokens. Router provides the reference of the newly generated URL. Therefore the mapped URL is generated for the incoming request.

Creating Routes

Route class is the standard implementation of IRouter. Therefore this class has a method called MapRoute that can map any incoming request to appropriate route. However, this method doesn’t take input for request handler, therefore, it uses the  default route handler. Default handler is responsible to communicate to the matched controller and action.

These are some ways to create routing in an application. Once the route is established it can follow the workflow between different middle-ware.

Entity Framework Core

Entity Framework (EF) Core is the first step for the future EF Core, therefore, it is designed to support the modern application requirement. Some of the main feature are that it is lightweight, extensible, and cross-platform. Following are some important feature:

In-Memory Provider:

This enables In-Memory database provider for Entity framework (EF) core applications. For different purpose, e.g. caching, session context, In-Memory database is popular among developers. However in  Entity framework (EF) core applications,  In-Memory database only support testing.  In for Entity framework (EF) core applications it is very easy to install an in-memory database. The following command can install it using NuGet package.

Shadow Properties:

This is an excellent feature for Entity framework (EF) core. This enables an additional layer of abstraction by preventing properties of model in database from being exposed if they are configured not to be. Mostly, identifier, foreign key are the properties those are vulnerable to security breach and required to be hidden from client application. Shadow properties provides that feature.

However, for different internal purpose, these shadow properties need to be used in backend services, Therefore,  ChangeTracker API is used to read the value for any shadow properties.

Fluent API is used for marking any property of the model as shadow property by overriding OnModelCreating method.

What are the new features of Entity Framework Core 2.0?

MSDN announce the new Entity framework (EF) core 2.0 on August 2017. Along with and ASP .Net Core 2.0. The new feature in this version are as following:

  • EF Core 2.0 mainly supports the standard .NET Core 2.0. It also enabled around 32,000 API s for.NET Framework, .NET Core, Mono, Xamrian and the ultimate future Universal Windows Platform
  • It has made a dynamic change in queries. Queries are faster and some of the existing queries are obsolete where as some other new patterns have been introduced. Similarly, some LINQ are directly convertible to SQL pattern. For example, EF.Functions.Like() in a LINQ can be translated to LIKE in SQL.
  • Defining the relationship between Entities have been changed significantly. For example, it is possible to make an owner relationship between two entities.  For example, A student object owns only one address of his or her home.
    Therefore, the relation between Student class and HomeAddress class could be:
  • It is possible to use filter in the model . for example, Here is a filter added to Student class to find the students who have failed on exam,
    Now if we try to filter out any array using the filter, it would return the sublist of the students who has failed by matching the id whith the id those are included in the filter.
  • Performance has been improved significantly. Now for each reqest, it is no longer necessary to create a new instac for requested service, using the configuring for service registration of their DbContext it is possible to use a pool of pre-created instances.
  • Database scalability is another feature to mention in new version.

Further what are the missing features that were available in EF6 but not in EF Core 1.0?

Here is a list of items those are existing in EF 6 but not in EF Core

  • Inheritance: Table per type (TPT)
  • Inheritance: Table per concrete class (TPC)
  • Many-to-many without join entity
  • Spatial data
  • Graphical visualization of model
  • Graphical model editor
  • Model format: EDMX (XML)
  • Create model from database: VS wizard
  • Update model from database
  • Entity splitting
  • Loading related data: Lazy
  • Raw SQL queries: Non-model types
  • Stored procedure
  • Seed data
  • Lifecycle hooks (events, interception)
  • DB2 provider

Following are some items those are available in EF core but not in EF6

  • Shadow state properties
  • Alternate keys
  • Key generation: Client
  • Global query filters
  • Field mapping
  • Mixed client/server evaluation
  • Better query feature
  • Batching of statements
  • DbContext pooling
  • In-Memory Database Provider
  • Platform support for .NET Core (Console, ASP.NET Core), Mono, Xamarian Universal Windows Platform

The next version of Entity Framework is already ongoing which includes a whole bunch of new feature and fix for existing bugs.

Your First ASP.NET Core Application

Let’s create a basic ASP.NET Core MVC Application by following a step by step approach.

Step 1:

  • Open Visual Studio 2015 and Select → File → New->Project (It will open the Project Template).
  • Select → .NET CoreASP.NET Core Web Application(.NET Core) and name the project.
  • Choose the location where we want to save and press the OK button as we used to do previously.Visual Studio 2015 Create Project
  • Next It will open the Project Template wizard. Select Empty template and View Engine as Razor.
  • Click OK, Solution Explorer and working environment will be opened.

Step 2:

Let’s add a Controller in our application. This controller file is just like C# classes which contains multiple public methods also called action methods. It’s the controller’s responsibility to process the request, building the appropriate model and redirecting to a particular View. To keep this example, we are not using Model but just rendering the text response to View.

  • To add a new Controller, In Solution Explorer → right click the Controllers folder, select Add → New Item → Controller.
  • Named the Controller as “TestAssignment” and click Add.ASP.NET MVC Controller
  • Under the Controllers file (TestAssignment), having the following default code.Controller to View
    The above code defines a public method Index inside our TestAssignmentController and returns a View object.

Step 3:

  • In this default code, Right click on View() method.
  • Select → AddView.Add a View to ASP.NET Core App
  • Give the Name to View as “Index”  and View Engine as Razor (.cshtml). Click “Add” button.ASP.NET Core View
  • After clicking Add button , The Solution explorer will be updated as follows:Visual Studio 2015 Solution Explorer
    It added a new .cshtml file inside Views/TestAssignment folder with the following code:Index in Visual Studio 2015
  • We have to update the Body of the HTML tag , As whatever we want to get.

Step 4:

  • Finally run the application by Click run Button.
  • The following output in the browser, the application first calls the Controller which in revert back calls this View and gives this  output which is expected as follows:ASP.NET Core App Running

Purpose of this basic ASP.NET Core Example is to familiarize you with environment. More practical applications with extensive use of technology will be followed.

ASP.NET Core with Angular 2
Build a Real-world App with ASP.NET Core and Angular 2 (4+)

  • Build a full-stack web app with ASP.NET Core, Entity Framework Core and Angular 2 & 4.
  • Implement a Clean & Decouple Architecture.
  • Properly implement the repository and unit of work patterns.
  • Troubleshoot common runtime errors.
  • Test APIs using PostMan.
  • Integrate ASP.NET MVC/Core with Angularjs.
  • Understand and apply the Dependency Inversion Principle (DIP).
  • Use the new dependency injection feature in ASP.NET Core.
  • Build APIs with ASP.NET Core
  • and more….

Take this Online Course at Discounted Price

This ASP.NET Core Tutorial is just the beginning explaining core concepts and creating a basic ASP.NET Core Web application. You will find more detailed practical examples on ASP.NET Core soon here. You can follow below for more helpful material regarding related technologies here: