Starting With ASP.NET Core

We all are working on ASP.NET Web Applications using Visual Studio. When Microsoft released the first version of ASP.NET in  2002 with version 1.0 of the .NET Framework, it had fewer features. Gradually, ASP.NET framework evolved to reach the current state. We have seen multiple versions that give us more features. They are easier and more compatible to the user. We have seen ASP.NET, ASP.NET 2.0, ASP.NET MVC, ASP.NET Webpages make the Application development easy and also help to add lot more value to the business needs. 

There were some shortcomings in .NET based Applications, which are, that we can’t run the Application from the different platforms like Windows, Linux, MAC or  Symbian Operating systems. For example, we cannot run ASP.NET Application running on Windows 7 operating system in Linux operating system . To run in Linux Operating System, we need to write the Application using Mono framework . Other drawbacks were Microsoft .NET framework is not an open source and it is not integrated with the client side frameworks.

Recently, Microsoft came up with the new framework, which can run on all the hardware, all the platforms, and can run anywhere. The new framework addressed the need of the next generation needs of the modern Web like: 

  • Cross Platform
  • Open Source
  • Mobile / Tablet First
  • Responsive Design
  • Client Frameworks
  • Cloud Ready

To address these concerns, Microsoft came up with a totally modular, open source and cross platform framework i.e. ASP.NET core.

  

.NET framework 4.6 is a full framework for everything related to .NET and is confined to Windows only. ASP.NET Core is a subset of .NET framework 4.6, which is mainly optimized for the multi-platform and the cloud deployments.

Features of ASP.NET Core

  • ASP.NET core is modular, cross-platform and an open source software development framework given by Microsoft.
  • ASP.NET Core works with two runtime environments (.NET Core and .NET Framework). .NET core is for all the platforms (Windows, Linux and MAC) whereas .NET framework is for Windows.
  • When we create a new project in ASP.NET Core Web Application, it includes only required dependencies to the Application.
  • ASP.NET  Core Platform Standard is the new approach for addressing the real binary portability with PCL.
  • ASP.NET Core comes with a command line tool named “DNVM – .NET version manager“. It allows to upgrade or install new dnx version.
  • ASP.NET Core works on the file system, which allows the faster development cycle. It detects the code changes (even outside Visual Studio), compiles into the memory and loads the Application.
  • ASP.NET  Core has an inbuilt support for Dependency injection. ASP.NET Core includes a simple built-in container (represented by the IServiceProvider interface), that supports Constructor injection by default and ASP.NET makes certain services available through DI.
  • It is also Cloud ready as it supports an environment-based configuration.
  • It uses completely new light-weight and modular HTTP request pipeline.
  • HTTPHandler and HTTPModules are removed from the framework now. Now, they are replaced with Middleware, which can be injected as a dependency, when required.
  • JSON is preferred over XML for the configuration settings in the project organization.
  • There is no global.asax file now. global.asax is now Startup.cs, which is an entry point for the Application itself.
  • The new Project.json file is the heart of your project. It defines the dependencies and runtime to use and defines build and publish setup. It defines project as DNX project.  DNX is the .NET Execution. It executes with the help of the compiled binary in ASP.NET Core project.
  • wwwroot directory in project is for static content like css, Js, images. It is the default root of your Server. If a request comes in for a static file on the disk, if the file is in this folder, it can go back to the client. The name can be changed from project.json file.
  • Now, we can directly add the reference of any assembly just via typing. Add assembly name with the version in project.json file and Visual Studio will add the reference for us.
  • ASP.NET Core is designed to integrate seamlessly with a variety of client-side frameworks, including AngularJS, KnockoutJS and Bootstrap.
  • ASP.NET Core has also an inbuilt support for the client side package manager bower. It now also supports JavaScript task runners’ grunt/gulp, Web project scaffolding tool Yeoman.
  • It has an integrated inbuilt support of TypeScript .
  • ASP.NET Core  comes with Unified Programming Model for MVC6 and Web API. In the previous versions of ASP.NET MVC, MVC controllers were different from Web API controllers. MVC controller is used in the System.Web.MVC.Controller base class and a Web API controller is used in the System.Web.Http.ApiController base class.
  • When we create a new class file project, it becomes .xproj instead of csproj. The new project file doesn’t include manifest and the list of all the files, that are included in our project, as earlier with .csproj.
  • By default, a class library project when compiled becomes a NuGet package, instead of DLL.

Microsoft .NET framework is an open source technology after the release of .NET Core. Anyone can download, use the framework and contribute to the required package as an open source.



To work with ASP.NET Core, download Visual Studio and .NET core from Microsoft Website, as shown in the screenshot, given below:



Let us create a new project in Visual Studio.



When we create a new project, select “ASP.NET Core Web Application” and click OK.



Select the Web Application and click OK.

 

If you want to deploy in Cloud, give your Azure account information and click create. Once we create the project, the file organization and the folder organization is shown below:



The major files and folder changes in ASP.NET Core compared to the earlier versions are:
 

  • global.json
  • wwwroot
  • appsetting.json
  • gulpfile.js
  • Program.cs
  • Project.json
  • Startup.cs

If we observe, there are new files and drastic changes in terms of file organization and code structuring.Let us see these files and their purpose.

global.json

The global.json file contains the setting, which is required for the solution level as a whole. The settings defined in global.json applies to all the projects in the solution. If this file is opened, by default, you will see the code, given below:

  1. {  
  2.   "projects": [ "src""test" ],  
  3.   "sdk": {  
  4.     "version""1.0.0-preview1-002702"  
  5.   }  
  6. }  

wwwroot

wwwroot folder contains all the css, bootstrap, jquery, images, jqueryvalidations files required for the Application.



One important file to observe here is bower.json, which contains the details of the referred version of the script, styles, bootstrap versions. Microsoft recommends to get the client side dependencies from bower, using “Manage Bower Packages” option.The reason behind this is that Microsoft does not have the control of the these external component files, when these script, styles or bootstrap related new versions have come up . To update the client side dependency file, right click the Application, select the “Manage Bower Packages” option and you will get the option of updating, uninstalling,or  installing the dependency, as per your choice.



Appsettings.json

Appsettings.json file is used to define the Application related settings like connection string, loggin settings or any key through which we can read and can be used in the code. When this file is opened, we get the content of this file, as shown below:
  1. {  
  2.   "ApplicationInsights": {  
  3.     "InstrumentationKey"""  
  4.   },  
  5.   "ConnectionStrings": {  
  6.     "DefaultConnection""Server=(localdb)\\mssqllocaldb;Database=aspnet-TestApp-87d57b2e-04f2-4a2e-8453-9aa35cc5cbf2;Trusted_Connection=True;MultipleActiveResultSets=true"  
  7.   },  
  8.   "Logging": {  
  9.     "IncludeScopes"false,  
  10.     "LogLevel": {  
  11.       "Default""Debug",  
  12.       "System""Information",  
  13.       "Microsoft""Information"  
  14.     }  
  15.   }  
  16. }  

Project .json

This file is used to define the project settings and Server side dependencies. It contains the configuration for the dependencies, framework version, tools configured for the project, Builtoptions, Runtime options, Publishoptions etc. In .NET, core is broken down into the granular modules so that we can use only what is necessary to keep the memory management efficiently.

If we open this file, we will see the content of the file, as shown below: 
  1. {  
  2.   "userSecretsId""aspnet-TestApp-87d57b2e-04f2-4a2e-8453-9aa35cc5cbf2",  
  3.   
  4.   "dependencies": {  
  5.     "Microsoft.NETCore.App": {  
  6.       "version""1.0.0-rc2-3002702",  
  7.       "type""platform"  
  8.     },  
  9.     "Microsoft.ApplicationInsights.AspNetCore""1.0.0-rc2-final",  
  10.     "Microsoft.AspNetCore.Authentication.Cookies""1.0.0-rc2-final",  
  11.     "Microsoft.AspNetCore.Diagnostics""1.0.0-rc2-final",  
  12.     "Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore""1.0.0-rc2-final",  
  13.     "Microsoft.AspNetCore.Identity.EntityFrameworkCore""1.0.0-rc2-final",  
  14.     "Microsoft.AspNetCore.Mvc""1.0.0-rc2-final",  
  15.     "Microsoft.AspNetCore.Razor.Tools": {  
  16.       "version""1.0.0-preview1-final",  
  17.       "type""build"  
  18.     },  
  19.     "Microsoft.AspNetCore.Server.IISIntegration""1.0.0-rc2-final",  
  20.     "Microsoft.AspNetCore.Server.Kestrel""1.0.0-rc2-final",  
  21.     "Microsoft.AspNetCore.StaticFiles""1.0.0-rc2-final",  
  22.     "Microsoft.EntityFrameworkCore.SqlServer""1.0.0-rc2-final",  
  23.     "Microsoft.EntityFrameworkCore.Tools": {  
  24.       "version""1.0.0-preview1-final",  
  25.       "type""build"  
  26.     },  
  27.     "Microsoft.Extensions.Configuration.EnvironmentVariables""1.0.0-rc2-final",  
  28.     "Microsoft.Extensions.Configuration.Json""1.0.0-rc2-final",  
  29.     "Microsoft.Extensions.Configuration.UserSecrets""1.0.0-rc2-final",  
  30.     "Microsoft.Extensions.Logging""1.0.0-rc2-final",  
  31.     "Microsoft.Extensions.Logging.Console""1.0.0-rc2-final",  
  32.     "Microsoft.Extensions.Logging.Debug""1.0.0-rc2-final",  
  33.     "Microsoft.VisualStudio.Web.BrowserLink.Loader""14.0.0-rc2-final",  
  34.     "Microsoft.VisualStudio.Web.CodeGeneration.Tools": {  
  35.       "version""1.0.0-preview1-final",  
  36.       "type""build"  
  37.     },  
  38.     "Microsoft.VisualStudio.Web.CodeGenerators.Mvc":  {  
  39.       "version""1.0.0-preview1-final",  
  40.       "type""build"  
  41.     }  
  42.   },  
  43.   
  44.   "tools": {  
  45.     "Microsoft.AspNetCore.Razor.Tools": {  
  46.       "version""1.0.0-preview1-final",  
  47.       "imports""portable-net45+win8+dnxcore50"  
  48.     },  
  49.     "Microsoft.AspNetCore.Server.IISIntegration.Tools": {  
  50.       "version""1.0.0-preview1-final",  
  51.       "imports""portable-net45+win8+dnxcore50"  
  52.     },  
  53.     "Microsoft.EntityFrameworkCore.Tools": {  
  54.       "version""1.0.0-preview1-final",  
  55.       "imports": [  
  56.         "portable-net45+win8+dnxcore50",  
  57.         "portable-net45+win8"  
  58.       ]  
  59.     },  
  60.     "Microsoft.Extensions.SecretManager.Tools": {  
  61.       "version""1.0.0-preview1-final",  
  62.       "imports""portable-net45+win8+dnxcore50"  
  63.     },  
  64.     "Microsoft.VisualStudio.Web.CodeGeneration.Tools": {  
  65.       "version""1.0.0-preview1-final",  
  66.       "imports": [  
  67.         "portable-net45+win8+dnxcore50",  
  68.         "portable-net45+win8"      
  69.       ]  
  70.     }  
  71.   },  
  72.   
  73.   "frameworks": {  
  74.     "netcoreapp1.0": {  
  75.       "imports": [  
  76.         "dotnet5.6",  
  77.         "dnxcore50",    
  78.         "portable-net45+win8"  
  79.       ]  
  80.     }  
  81.   },  
  82.   
  83.   "buildOptions": {  
  84.     "emitEntryPoint"true,  
  85.     "preserveCompilationContext"true  
  86.   },  
  87.   
  88.   "runtimeOptions": {  
  89.     "gcServer"true  
  90.   },  
  91.   
  92.   "publishOptions": {  
  93.     "include": [  
  94.       "wwwroot",  
  95.       "Views",  
  96.       "appsettings.json",  
  97.       "web.config"  
  98.     ]  
  99.   },  
  100.   
  101.   "scripts": {  
  102.     "prepublish": [ "npm install""bower install""gulp clean""gulp min" ],  
  103.     "postpublish": [ "dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" ]  
  104.   }  
  105. }  

gulpfile.js

gulpfile.js provides a functionality, that allows the developers the cleaning, bundling and minification of CSS and JS files. Right click the gulpfile.js and you will be able to see the “Task Runner Explorer”, where we can minify our styles and script files.

Minification is the process which is used to reduce the size of the page between the Client and Server communication process.



Program.cs

The Program.cs file has the main method, which is responsible to configure and run the app. The code of the program.cs looks, as shown below. The WebHostBuilder class uses Startup class, uses a Web Server like IIS and Kestrel; a Web Server to process the Application.

  1. public class Program  
  2.     {  
  3.         public static void Main(string[] args)  
  4.         {  
  5.             var host = new WebHostBuilder()  
  6.                 .UseKestrel()  
  7.                 .UseContentRoot(Directory.GetCurrentDirectory())  
  8.                 .UseIISIntegration()  
  9.                 .UseStartup<Startup>()  
  10.                 .Build();  
  11.   
  12.             host.Run();  
  13.         }  
  14.     }  

In ASP.NET Core, we can run the Application with IIS, Apache or any Web Server as IIS is used to purely design the Web Server for Windows OS. For testing multiple Web Servers, we can run the Application, using Kestrel; a Web Server. To do this, select the project name from the launch menu and click F5.



On Clicking F5 we will get the Page and Kestrel web server running on the command prompt.



Startup.cs

The startup.cs file is used to read the entire configuration related setting of the Application. There is no global.asax file in .NET Core and most of the things that we were doing in global.asax needs to be done in startup.cs.

For example, routing earlier we were putting in global.asax.cs, now we need to putit in startup.cs. The startup.cs provides the feature of putting services or any other component as a dependency injection. Logic like authentication, validation or request pipeline optimization etc. can be defined as services and can be injected here.The http module, http handler etc. are removed now. In .NET Core, they are referred as middleware. In Startup.cs, we need to define what our Application is trying to use; either MVC or static file as
 app. 

The configureServices is a method where we can define all the dependencies and we can define the object life time during the creation of an object (services.AddTransient or services.AddSingleton etc).

 

  1. Startup.Cs  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Linq;  
  5. using System.Threading.Tasks;  
  6. using Microsoft.AspNetCore.Builder;  
  7. using Microsoft.AspNetCore.Hosting;  
  8. using Microsoft.AspNetCore.Identity.EntityFrameworkCore;  
  9. using Microsoft.EntityFrameworkCore;  
  10. using Microsoft.Extensions.Configuration;  
  11. using Microsoft.Extensions.DependencyInjection;  
  12. using Microsoft.Extensions.Logging;  
  13. using TestApp.Data;  
  14. using TestApp.Models;  
  15. using TestApp.Services;  
  16.   
  17. namespace TestApp  
  18. {  
  19.     public class Startup  
  20.     {  
  21.         public Startup(IHostingEnvironment env)  
  22.         {  
  23.             var builder = new ConfigurationBuilder()  
  24.                 .SetBasePath(env.ContentRootPath)  
  25.                 .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)  
  26.                 .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);  
  27.   
  28.             if (env.IsDevelopment())  
  29.             {  
  30.                 // For more details on using the user secret store see http://go.microsoft.com/fwlink/?LinkID=532709  
  31.                 builder.AddUserSecrets();  
  32.   
  33.                 // This will push telemetry data through Application Insights pipeline faster, allowing you to view results immediately.  
  34.                 builder.AddApplicationInsightsSettings(developerMode: true);  
  35.             }  
  36.   
  37.             builder.AddEnvironmentVariables();  
  38.             Configuration = builder.Build();  
  39.         }  
  40.   
  41.         public IConfigurationRoot Configuration { get; }  
  42.   
  43.         // This method gets called by the runtime. Use this method to add services to the container.  
  44.         public void ConfigureServices(IServiceCollection services)  
  45.         {  
  46.             // Add framework services.  
  47.             services.AddApplicationInsightsTelemetry(Configuration);  
  48.   
  49.             services.AddDbContext<ApplicationDbContext>(options =>  
  50.                 options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));  
  51.   
  52.             services.AddIdentity<ApplicationUser, IdentityRole>()  
  53.                 .AddEntityFrameworkStores<ApplicationDbContext>()  
  54.                 .AddDefaultTokenProviders();  
  55.   
  56.             services.AddMvc();  
  57.   
  58.             // Add application services.  
  59.             services.AddTransient<IEmailSender, AuthMessageSender>();  
  60.             services.AddTransient<ISmsSender, AuthMessageSender>();  
  61.         }  
  62.   
  63.         // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.  
  64.         public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)  
  65.         {  
  66.             loggerFactory.AddConsole(Configuration.GetSection("Logging"));  
  67.             loggerFactory.AddDebug();  
  68.   
  69.             app.UseApplicationInsightsRequestTelemetry();  
  70.   
  71.             if (env.IsDevelopment())  
  72.             {  
  73.                 app.UseDeveloperExceptionPage();  
  74.                 app.UseDatabaseErrorPage();  
  75.                 app.UseBrowserLink();  
  76.             }  
  77.             else  
  78.             {  
  79.                 app.UseExceptionHandler("/Home/Error");  
  80.             }  
  81.   
  82.             app.UseApplicationInsightsExceptionTelemetry();  
  83.   
  84.             app.UseStaticFiles();  
  85.   
  86.             app.UseIdentity();  
  87.   
  88.   
  89.             app.UseMvc(routes =>  
  90.             {  
  91.                 routes.MapRoute(  
  92.                     name: "default",  
  93.                     template: "{controller=Home}/{action=Index}/{id?}");  
  94.             });  
  95.         }  
  96.     }  
  97. }  
These are the some basic bullet points, which each .NET developer should keep in mind.
  • DNX – DNX refers to Dot net Execution. It executes by compiled binary in ASP.NET core project.
  • DNVM – DNVM refers to Dot net Version Manager. It manages all the framework versions in an ASP.NET Core project.
  • DNU – It helps in getting the references and does compiling in ASP.NET Core project.
  • NPM – It refers to NuGet Package Manager and is used to manage various dependencies in the project.
  • ASP .NET 5.0 is now industry wide renamed to “ASP .NET Core 1.0”
  • MVC 6 is now industry wide renamed to “ASP .NET Core MVC”.
  • Entity Framework 7 is now industry wide renamed to “Entity Framework Core 1.0
  • ASP.NET Web forms are removed in ASP.NET Core. All the Web pages are followed in MVC architecture style.
  • ASP.NET core will be the next version of .NET Web development framework but it  is not a stable platform yet . To build our customer project, proper POC should be done before starting our actual implementation or  we should wait once, everybody adopts the framework.
  • There are two versions, named RC1 and RC2 for ASP .NET Core 1.0, while RC2 is the latest one.

I hope you understood the basic concepts of ASP.NET Core and what the next generation of .NET development framework is going to be. Thanks for your valuable time for reading it.

Up Next
    Ebook Download
    View all
    Learn
    View all