ASP.NET Core Fundamentals Step By Step

Introduction to ASP.Net Core

ASP.NET Core is an open source cross platform framework to build modern Cloud based Applications. We can develop and run ASP.NET Core Applications cross platforms on Windows, Mac and Linux.

ASP.Net Core

.NET Framework 4.6 vs .NET Core

ASP.Net Core

.NET Framework 4.6

  • It is our old enhanced framework that we have been using for more than a decade.
  • It is not  open source.
  • It can target only Windows OS.
  • It has all the components like Windows Form Application. ASP.NET Web Forms, ASP.NET MVC, ASP.NET Web API, ASP.NET SignalR, ASP.NET Web Pages, WPF, WCF etc.

.NET Core

.NET Core is a new framework, which is similar to .NET framework maintained by Microsoft and the .NET community on GitHub (https://github.com/dotne).

  • It is open source
  • It can target Windows, Linux & Mac OS.
  • It does not have all the components. It just has Net Core and Universal Windows app.

ASP.NET Vs ASP.NET Core

ASP.Net Core

ASP.NET

  • Old .NET framework is a language, which is neutral in Windows platform.
  • It only works in Windows OS.

ASP.NET Core

  • It is the redesign of an ASP.NET.
  • It is an open source.
  • .NET Core is a platform neutral.
  • It can target to Windows, Linux & Mac OS.
  • A unified way of building Web UI and Web APIs.
  • It is very easy to integrate a variety of client-side frameworks, including AngularJS, KnockoutJS and Bootstrap.
  • No ASP.NET Web Forms :(
  • There is no separate Web API and MVC and its combined together.
  • NET Web Application (.Net Framework) template is the old .Net framework
  • NET Core Web Application (.Net Core) template is a platform neutral
  • NET Core Web Application (.Net Framework) template is for Windows platform
  • MVC 6 renamed as MVC Core or ASP.NET Core
  • NET Core does not support WPF, Win Forms, SignalR etc.
  • NET Core supports either MVC or Web API Application.
  • NET Core has different class libraries whereas the base class libraries are same but based on OS; the compiled code is different.

Getting Started With ASP.NET Core

Install Visual Studio 2015 Update 3.

Install .NET Core for Visual Studio.

(https://www.microsoft.com/net/core#windowsvs2015)

Or

Install Visual Studio 2017

(https://www.visualstudio.com/thank-you-downloading- visual-studio/?sku=Community&rel=15)

When you select the project, type Visual C# => Web. Now, you will get 3 project types, as shown below.

  • NET Web Application (.NET Framework).
  • NET Core Web Application (.NET Core).
  • NET Core Web Application (.NET Framework).

ASP.NET Web Application (.NET Framework)

This project type is for old .NET framework. The screenshot is given below for reference.

ASP.Net Core

ASP.NET Core Web Application (.NET Core)

This project type is for ASP.NET Core Application cross-site platform. The screenshot is given below for reference.

ASP.Net Core

ASP.NET Core Web Application (.NET Framework)

This project type is for ASP.NET Core Application for Windows platform. The screenshot is given below for reference.

ASP.Net Core

Supported project templates ASP.NET Vs ASP.NET Core

ASP.Net Core

ASP.NET Core supports only 3 types of project templates, which are listed in the screenshot given above.

If we go with ASP.NET Core Empty template, this content does not have any content in it. You have to create your own project structure and from the scratch, you have to create/add the required files and folders, as per your need.

If you go with ASP.NET Core Web API template, Views folder will not be created for you. If you want it, you can create Views folder and subsequently you can use the project as ASP.NET Core MVC in addition to Web API project.

If you go with ASP.NET Core Web Application template, Views folder automatically will be created for you. If you want it, you can delete Views folder and few other folders, which are not required by you. Now, you can use the project as ASP.NET Core Web API project.

Let's say that you have created ASP.NET Core Web Application. The project structure looks, as shown below.

ASP.Net Core

Either an ASP.NET Core Web Application or Web API Application execution starts from Program.cs file, where you will see the set of the method called object chaining. In object chaining, each method call is responsible for one job. Finally, the object chaining assigns to a variable and subsequently we should run the assigned variable to execute the object chaining. Unless we call Run() method, the object chaining will not be called. The brief description for each method call's responsibility in object chaining is given below.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.IO;  
  4. using System.Linq;  
  5. using System.Threading.Tasks;  
  6. using Microsoft.AspNetCore.Hosting;  
  7.   
  8. namespace WebAppCoreSampleApp  
  9. {  
  10.     public class Program  
  11.     {  
  12.         public static void Main(string[] args)  
  13.         {  
  14.             var host = new WebHostBuilder()  
  15.                 .UseKestrel()  
  16.                 .UseContentRoot(Directory.GetCurrentDirectory())  
  17.                 .UseIISIntegration()  
  18.                 .UseStartup<Startup>()  
  19.                 .Build();  
  20.             host.Run();  
  21.         }  
  22.     }  
  23. }  

WebHostBuilder()

The WebHostBuilder() call is responsible to create a host, which starts the Server for ASP.NET Core Application.

UseKestrel()

Every ASP.NET Core Application runs under Kestrel Server by default, which does not mean that you cannot use IIS Server. We can use IIS Server as well but if we use IIS Server then IIS Server internally talks with Kestrel Server again. Without Kestrel Server, we cannot run ASP.NET Core Application.

ASP.Net Core

UseContentRoot(Directory.GetCurrentDirectory())

UseContentRoot() call is not required, if you are going with ASP.NET Core Web API Application, whereas if you want to create an ASP.NET Core Web Application, then this method call is required and it is mandatory because this method call determines from where the content files like .HTML or MVC view files will be loaded. UseContentRoot(Directory.GetCurrentDirectory()) method call refers wwwroot folder as the Application's content root. It is wwwroot, which is a resource folder, where you can place all your static(.html) and dynamic files which can be available throughout the world.

UseIISIntegration()

If you want to run the ASP.NET Core Application in IIS Server, then the UseIISIntegration method should be called as a part of an object chaining to build the host.

Hence, now to display the welcome message in an ASP.NET Core Application, we have to configure a Delegate in the object chaining with Configure object.

  1. var host = new WebHostBuilder()  
  2.     .UseKestrel()  
  3.     .UseContentRoot(Directory.GetCurrentDirectory())              
  4.     .UseIISIntegration()  
  5.     .Configure(app =>  
  6.     {  
  7.         app.Run(async (context) => await context.Response.WriteAsync("Welcome to ASP.Net Core!"));  
  8.     })  
  9.     .Build();  
  10. host.Run();  

When you run the Application under Kestrel Server, then you will get the screenshot given below.

ASP.Net Core

When you run the Application under IIS Express, then you will get the screenshot given below.

ASP.Net Core

UseStartup<Startup>()

To configure everything in object chaining with Configure call, Delegate is not the best way to handle everything because it causes maintenance issues. Instead of writing everything inside Delegate, it's good idea to configure a startup class, which results the code maintainability.

Like Global.asax file in ASP.NET Web Forms, Startup.cs file works in the same way. Startup.cs file has introduced to serve the way; the Global.asax file works to handle Application level events in an ASP.NET Application. It's not mandatory to name as Startup as you can give your own name, which you like and then map that name in UserStartup call in the object call chain.

The syntax to configure the startup file is given below.

  1. var host = new WebHostBuilder()  
  2.                 -----------------  
  3.                 -----------------  
  4.                 -----------------                  
  5.                 .UseStartup<Startup>()                  
  6.                 .Build();  
  7.             host.Run();  

Startup.cs class constructor

If the debugger reaches to this constructor, then this means that the WebHostBuilder has loaded is Startup class. This is the place to read the Application's configuration settings, as I have told you earlier that this class works just like a Global.asax file. Thus, if you want to achieve any task before starting any operation, then this is the right place. For example, if you want to enable the debug mode in development environment and in the same way, if you want to disable the debugging mode in production environment, then you can do it with the code snippet given below.

  1. public Startup(IHostingEnvironment env)  
  2. {  
  3.       ------------------  
  4.       ------------------  
  5.       ------------------  
  6.       if (env.IsEnvironment("Development"))  
  7.       {  
  8.           ------------------  
  9.           ------------------   
  10.           ------------------        
  11.       }  
  12.       if (env.IsEnvironment("Production"))  
  13.       {  
  14.           ------------------  
  15.           ------------------   
  16.           ------------------        
  17.       }  
  18.       ------------------  
  19.       ------------------   
  20.       ------------------         
  21.  }  

ConfigureServices()

The ConfigureServices() method is the place, where you can add the Services, which are required by the Application. ASP.NET Core Application uses an inbuilt Dependency Injection mechanism. If you want to inject DI in an ASP.NET Core Application, then you have to register them here. For example, you can register appsettings.json configuration file as a Service here. The code snippet given below shows you a sample ConfigureServices().

  1. // This method gets called by the runtime. Use this method to add services to the container  
  2. public void ConfigureServices(IServiceCollection services)  
  3.  {  
  4.        // Add framework services.  
  5.        services.AddApplicationInsightsTelemetry(Configuration);  
  6.        services.Add(ServiceDescriptor.Singleton<IConfiguration>(Configuration));              
  7.        services.AddMvc();  
  8.  }  

Configure()

This method is used to configure the middlewares, as shown below.

  • HTTP requests pipeline.
  • Security middleware.
  • Logging middleware.
  • Static file middleware etc.

If you are working on an ASP.NET Core Web Application, you will find a few more method calls in Configure() method, as shown below.

  1. public void Configure(IApplicationBuilder app)  
  2. {  
  3.     ------------  
  4.     ------------  
  5.     app.UseDefaultFiles();  
  6.     app.UseStaticFiles();  
  7.     ------------  
  8.     ------------  
  9. }  

Here, the order of the method calls is very important. When the Application runs, the UseDefaultFiles() method will look for the Application's default file is shown below.

  • default.htm
  • default.html
  • index.htm
  • index.html

While searching to see if the Applications gets anyone of these files, then the Application uses that file. If an application has multiple default files then the application searches on the above order. Ona  first come first served basis the application selects the file.

Run()

Once the object chaining builds, we can call by Run() method. The Web Application runs when Run() method is called from Main() method of Program.cs file and blocks the called thread until the host shuts down.

From the startup point Main() function till the startup configuration is loaded; the chain of middleware is invoked, as shown below with the screenshots given below.

ASP.Net Core

ASP.Net Core

Note that like Global.asax events, the Startup.cs constructor, ConfigureServices() and Configure() are called only once when the Application loads first. For the subsequent requests, the configuration of the Services and middleware will not load again because the host has already started and loaded it. Thus the subsequent requests will be taken directly, which are passed through the middleware chain.

Application Insights

Like Trace.axd file to trace the every request in an old .NET framework, in an ASP.NET Core Application, Application Insights does the same job of Trace.axd file. To achieve the same job, follow the steps given below.

Step 1

Add the piece of code given below in Startup.cs class's constructor development environment mode.

  1. public Startup(IHostingEnvironment env)  
  2. {  
  3.         ------------------  
  4.         ------------------  
  5.         ------------------  
  6.         if (env.IsEnvironment("Development"))  
  7.         {  
  8.             builder.AddApplicationInsightsSettings(developerMode: true);  
  9.         }  
  10.         ------------------  
  11.         ------------------  
  12.         ------------------  
  13.  }  

Step 2

Add the Application Insight service in ConfigureServices method.

  1. public void ConfigureServices(IServiceCollection services)  
  2. {  
  3.      ---------------  
  4.      ---------------  
  5.      services.AddApplicationInsightsTelemetry(Configuration);  
  6.      ---------------  
  7.      ---------------  
  8. }  

Step 3

Add the Application Insight request in Configure method.

  1. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)  
  2. {  
  3.      ---------------  
  4.      ---------------  
  5.      app.UseApplicationInsightsRequestTelemetry();  
  6.      ---------------  
  7.      ---------------  
  8. }  

Output

ASP.Net Core

Use of Properties -> launchSettings.json file

The launchSettings.json file is responsible for few of the Application configuration settings, as shown below.

  • If you want to change the default port number for IIS Express Server or for the Kestrel Server, then you can configure in this file.
  • In a similar way, if you wish to change the default Web API controller and action name, then you can configure in this file.
  • If you wish to change the default authentication mechanism, then you can configure here.
  • If you want to configure for IIS Production environment settings, then you can add a new block of code, which is next to IIS Express settings.

Likewise, you can configure many more settings in this file.

  1. {  
  2.   "iisSettings": {  
  3.     "windowsAuthentication"false,  
  4.     "anonymousAuthentication"true,  
  5.     "iisExpress": {  
  6.       "applicationUrl""http://localhost:51744/",  
  7.       "sslPort": 0  
  8.     }  
  9.   },  
  10.   "profiles": {  
  11.     "IIS Express": {  
  12.       "commandName""IISExpress",  
  13.       "launchBrowser"true,  
  14.       "launchUrl""api/values",  
  15.       "environmentVariables": {  
  16.         "ASPNETCORE_ENVIRONMENT""Development"  
  17.       }  
  18.     },  
  19.     "WebAppCoreConverter": {  
  20.       "commandName""Project",  
  21.       "launchBrowser"true,  
  22.       "launchUrl""http://localhost:5000/api/values",  
  23.       "environmentVariables": {  
  24.         "ASPNETCORE_ENVIRONMENT""Development"  
  25.       }  
  26.     }  
  27.   }  
  28. }  

Once you configure for IIS Production, then the new debug profile will be displayed, as shown below.

ASP.Net Core

Use of bower.json

Bower is the Package Manager, which automatically adds or updates client side packages (like jQuery, Bootstrap, TypeScript etc.) while we add or remove the listed packages in the JSON file.

ASP.Net Core

To change the default bower installation location, double click on .bowerrc file and change the target directory location on each adds or updates.

ASP.Net Core

  1. {  
  2.   "directory""wwwroot/lib"  
  3. }  

As the default location is set as "wwwroot/lib". So you can see the dependencies have installed in the same location. Below Screenshot for reference,

ASP.Net Core

Use of Web.config file

In ASP.NET Core application, the application configuration settings is now stored in appsettings.json file. For more details, please go through the below link:

http://www.c-sharpcorner.com/blogs/configuring-and-reading-application-settings-in-asp-net-core-application

Earlier, the application settings were stored in Web.config file. Now this file is used only for to set IIS hosting configuration.

Can we rename "wwwroot" folder?

Of course yes, If you want to rename the "wwwroot" folder name to some other name, let say "WebRoot" then you can achieve this with below 2 steps:

Step 1

Change the "wwwroot" folder to "WebRoot"

Step 2

Open the Program.cs file and add the below highlighted line in the Main() function.

  1. public static void Main(string[] args)  
  2. {  
  3.     var host = new WebHostBuilder()  
  4.         ----------  
  5.         ----------  
  6.         .UseWebRoot("WebRoot")  
  7.         ----------  
  8.         ----------  
  9.     host.Run();  
  10. }  

Can we change the default port number in ASP.Net Core application?

Of course yes, we know that the default port number for the Kestrel serve is 5000 (http://localhost:5000), if you want to change the host address as you wish then please go through the below link:

http://www.c-sharpcorner.com/blogs/configuring-asp-net-framework-version-and-customize-default-port-number-in-asp-net-core-application

Conclusion

Personally, I am a great fan of ASP.Net Core because Microsoft did a great job of redesigning the framework and releasing it as an open source to the outside world.

In my next article I will goa a little deeper on ASP.Net Core dependency injection.

Suggestions and feedback are always appreciated.

Happy coding!!

Up Next
    Ebook Download
    View all
    Learn
    View all