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.
.NET Framework 4.6 vs .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
- 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 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 Web Application (.NET Framework)
This project type is for ASP.NET Core Application for Windows platform. The screenshot is given below for reference.
Supported project templates ASP.NET Vs 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.
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.
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- using System.Threading.Tasks;
- using Microsoft.AspNetCore.Hosting;
-
- namespace WebAppCoreSampleApp
- {
- public class Program
- {
- public static void Main(string[] args)
- {
- var host = new WebHostBuilder()
- .UseKestrel()
- .UseContentRoot(Directory.GetCurrentDirectory())
- .UseIISIntegration()
- .UseStartup<Startup>()
- .Build();
- host.Run();
- }
- }
- }
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.
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.
- var host = new WebHostBuilder()
- .UseKestrel()
- .UseContentRoot(Directory.GetCurrentDirectory())
- .UseIISIntegration()
- .Configure(app =>
- {
- app.Run(async (context) => await context.Response.WriteAsync("Welcome to ASP.Net Core!"));
- })
- .Build();
- host.Run();
When you run the Application under Kestrel Server, then you will get the screenshot given below.
When you run the Application under IIS Express, then you will get the screenshot given below.
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.
- var host = new WebHostBuilder()
- -----------------
- -----------------
- -----------------
- .UseStartup<Startup>()
- .Build();
- 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.
- public Startup(IHostingEnvironment env)
- {
- ------------------
- ------------------
- ------------------
- if (env.IsEnvironment("Development"))
- {
- ------------------
- ------------------
- ------------------
- }
- if (env.IsEnvironment("Production"))
- {
- ------------------
- ------------------
- ------------------
- }
- ------------------
- ------------------
- ------------------
- }
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().
-
- public void ConfigureServices(IServiceCollection services)
- {
-
- services.AddApplicationInsightsTelemetry(Configuration);
- services.Add(ServiceDescriptor.Singleton<IConfiguration>(Configuration));
- services.AddMvc();
- }
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.
- public void Configure(IApplicationBuilder app)
- {
- ------------
- ------------
- app.UseDefaultFiles();
- app.UseStaticFiles();
- ------------
- ------------
- }
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.
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.
- public Startup(IHostingEnvironment env)
- {
- ------------------
- ------------------
- ------------------
- if (env.IsEnvironment("Development"))
- {
- builder.AddApplicationInsightsSettings(developerMode: true);
- }
- ------------------
- ------------------
- ------------------
- }
Step 2
Add the Application Insight service in ConfigureServices method.
- public void ConfigureServices(IServiceCollection services)
- {
- ---------------
- ---------------
- services.AddApplicationInsightsTelemetry(Configuration);
- ---------------
- ---------------
- }
Step 3
Add the Application Insight request in Configure method.
- public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
- {
- ---------------
- ---------------
- app.UseApplicationInsightsRequestTelemetry();
- ---------------
- ---------------
- }
Output
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.
- {
- "iisSettings": {
- "windowsAuthentication": false,
- "anonymousAuthentication": true,
- "iisExpress": {
- "applicationUrl": "http://localhost:51744/",
- "sslPort": 0
- }
- },
- "profiles": {
- "IIS Express": {
- "commandName": "IISExpress",
- "launchBrowser": true,
- "launchUrl": "api/values",
- "environmentVariables": {
- "ASPNETCORE_ENVIRONMENT": "Development"
- }
- },
- "WebAppCoreConverter": {
- "commandName": "Project",
- "launchBrowser": true,
- "launchUrl": "http://localhost:5000/api/values",
- "environmentVariables": {
- "ASPNETCORE_ENVIRONMENT": "Development"
- }
- }
- }
- }
Once you configure for IIS Production, then the new debug profile will be displayed, as shown below.
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.
To change the default bower installation location, double click on .bowerrc file and change the target directory location on each adds or updates.
- {
- "directory": "wwwroot/lib"
- }
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,
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.
- public static void Main(string[] args)
- {
- var host = new WebHostBuilder()
- ----------
- ----------
- .UseWebRoot("WebRoot")
- ----------
- ----------
- host.Run();
- }
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!!