In continuation of the article, where we discussed which variant is more appropriate for Docker containers .NET Core or .NET Framework, let us take a closer look at ASP.NET Core. Just to mention, .NET Core and ASP.NET Core are two independent technologies. Their histories intersect and they differ like the .NET Framework and ASP.NET. Anyway, in this article, we will review the history, advantages, and disadvantages of both ASP.NET Core and .NET Core. On top of that, we will provide the review of some changes occurred to the ASP.NET Core project architecture.

What is .NET Core, ASP.NET Core and Why They Were Created?

Millions of developers used and, obviously, still be using, ASP.NET 4.x to create web applications. It is a great technology and has a long history of development, going back to its first release in early 2002. A lot has been changed since then and something had to be changed with the framework itself to match these changes. There are at least a few major reasons that resulted in the creation of a new framework from scratch.

Firstly, many years Microsoft has been providing closed source software, and this deterred many developers, who were supporters of open source, from the use. Some of the Microsoft partners had access to the source code, but this is obviously not the same as open source. Even if you do not contribute to the source code, access to it can help you more clearly understand how exactly framework works and what exactly the system function which you call does. This also allows the community to contribute to the development process: improvements can be easy, quickly discussed, as well as problems solving. This is what developers did not have previously.

Secondly, .NET framework supports a particular platform, so no wonder that people associate it with Windows only. This fact also was a great downside for people, who cannot or do not want to use the Windows operating system.

Thirdly, .NET Framework has gradually refused the idea of completely separate side-by-side installations by having no separation between minor version and sometimes even major versions. So, for example, applications with two different versions of the .NET Framework will coexist with the risk of sharing dependencies, which can cause problems. As for ASP.NET, which is based on System.Web.dll, its architecture closely reflects the way the IIS processes requests, and, hence, segregation of ASP.NET from IIS is nearly impossible today. System.Web also contains many features in one module, which makes it very difficult to modularize functionality and change the system-level behavior of ASP.NET. So, you cannot get only some part of the functionality that you need – you get all in one or get nothing.

All these reasons gave impetus to rethink and change the approach of modeling of how the .NET platform should move forward. As a result, .NET Core and ASP.NET Core were created. They both have a Core in the name not without reason, this was done to avoid the impression that was just a new update of the .NET framework and to emphasize again their idea to change the concept itself. Let it not scare you, despite all these facts, it does not make your existing skills obsolete, it is just a major investment in the future of the whole platform.

Main Innovations and Advantages


As mentioned above, ASP.NET Core is a new, open source, modular, cross-platform, extensible, asynchronous, and much leaner framework. It is now a single framework that runs on top of either .NET Core 5 runtime (Core-CLR) or the .NET Framework runtime (CLR) and has a lot of advantages, most of which will be reviewed below.

In contrast to the monolithic .NET framework, .NET Core platform is delivered as a set of NuGet packages, that provide a small, discrete piece of functionality. This allows you to optimize applications, make them more lightweight and much leaner and also means that you can ship a private version of the .NET Core Framework for your specific application, without any risk that other application versions can change your application’s behavior. That is a key worth of ASP.NET Core, which is no longer based on System.Web.dll, – that it can run on multiple versions of .NET Core on the same machine. NuGet allows ASP.NET team to provide new functionality and fixes much easier and faster. In this way, if Microsoft provides an upgrade to any of the packages, you can just upgrade it and that is it – as simple as ABC. With ASP.NET Core 2.1 Microsoft has introduced a metapackage called Microsoft.AspNetCore.App, which contains all the libraries shipped by the .NET and ASP.NET teams, and provides direct support without locking you into specific versions of third-party dependencies. All of this improves the performance and scalability of applications.

Also, .NET Core and ASP.NET Core are now open sources. It is a great step up for the whole .NET community because it makes the development process transparent and clean, and also allows developers to be involved in the code review, bug fixing, providing new features, and of course, provides an opportunity to study the used libraries in detail. This also allows the community to ask questions, create bug reports right in the GitHub and get quick answers and help.

One implies the other, and open source enables Microsoft to extend the .NET unification to cross-platform development, as well. The .NET Core is having a single code base that can be used to build and support all the platforms, including Windows, Linux, and Mac OS. Obviously, some individual components, for example, such OS specific thing like a file system, require a separate implementation. The delivery model through NuGet allows to abstract those differences away. And the important part of this is that for developers, this is a single API, that runs on different platforms, they do not need to take care of it, because the package already contains different implementations for each of the environments. Configuration features also became more cross-platform-friendly by replacing the old ones with JSON or INI files and environment variables. Cross-platform also means that you have a more extensive range of operating systems which you can use for deployment because Azure will support ASP.NET Core in both Linux and Windows VMs – so it is up to you what to choose.

As a great plus for people, who do not want to install Visual Studio by virtue of any reason (the e.g. non-Windows machine is used, or favoring lighter-weight tools), now you can also choose Visual Studio Code, Atom, Emacs, and so on, as IDE or even work with command prompt. For example, Visual Studio Code is the cross-platform code editor for Linux, MacOS, and Windows. With it, you can build, debug and run ASP.NET Core web applications, Node web application or .NET Core console applications with the ability to use IntelliSense, code completion and Git integration. If you are a command-line-tools partisan, you will be glad to hear that everything that is involved in building, compiling or running .NET Core applications can be done using the command line.

Due to ASP.NET Core smaller footprint, there are also some performance benefits that are specific to .NET Core, but, most of them are applied to both the .NET Framework and .NET Core.

As for ASP.NET and IIS ligament, now ASP.NET Core actually does not require IIS to run. It ships with the following server implementations:

The most popular among them is Kestrel and it is also a default one in ASP.NET Core templates. When you create a new project in Visual Studio, it is automatically configured to run in Kestrel. The later is actually based on libuv, which is used for I/O work and supports running multiple event loops. However, despite the fact, that it is fast, cross-platform and has been optimized for throughput performance, it does not provide all functionality as a full-featured Web service (like IIS) provides no port sharing, easy SSL configuration, URL rewrites, and so on. Some of these features may appear in the future, but today Kestrel is normally used with a reverse proxy server, such as IIS, Nginx, or Apache. This is also a plus and a minus at the same time. Kestrel is really fast, in fact, six times faster than Node.js for static and plain text operations, and it also provides better request processing performance, but all of this is achieved due to it is not а feature-rich web server. It might sound strange at first, why it was needed to create such a web server if you still need to use a proxy server, but, without it, you are not able to start your application on different platforms without changes. That is to say, without Kestrel on other cross-platform web servers, the ASP.NET Core application code would have changed for each of these web servers to satisfy their startup criteria.

As you can see ASP.NET Core is a major change which is no matter what did not lose overarching concepts that you have learned with existing versions of ASP.NET. You still can use frameworks like MVC, Web API, SignalR and their syntax is not going to change extremely, as well as business logic written using Entity Framework. It is also still the same C#, F#, etc. code and the .NET Framework is behind these all. In the end, the ultimate goal was not to replace .NET Framework with .NET Core but to add an alternative for developers, engage the new community, provide a brand-new stack to fit new changes in the development and extend the platform in the future.

.NET Core and ASP.NET Core Disadvantages

Such a young technology, of course, cannot have some disadvantages. Below are some of them with a brief explanation.

First of all, some of the .NET Framework technologies are not available in the current version of .NET Core. Actually, some of them planned to be available with later releases, but others might never be available. Below is a short list of the scenarios when you cannot use .NET Core:

There are a lot of discussions in GitHub threads on the subject of porting .NET Framework libraries to .NET Core, and this is a really good example of how open source may impact on the project development. If you open these threads, you will see that on each issue Microsoft employees answer about plans of porting technologies, discuss with the community the purposes why they needed this porting to know what exactly is necessary for developers. Obviously, there will be technologies that will not be ported at all, since they are related to the Windows operating system when .NET Core was born to provide cross-platform support.

Now, after we have reviewed all major changes in the .NET Core and ASP.NET Core let us move towards a new application structure and changes, which persist in a new type of the project.

ASP.NET Core Fundamentals

In this paragraph, we will create a test project to review changes in the structure on a real example. Assume that you have at least once created a new project with Visual Studio, that is why we will review a variant of creating a new solution with the project together by using a console.

To create a solution, open the console (we will use for this example Windows PowerShell, but you can use command prompt as well) and run next command:

dotnet new sln n reviewCoreApp

Here dotnet new – a command, with which you can create a new project, configuration file, or solution based on the specified template with all needed dependencies. In it, we indicated that we want to create a Solution with an option sln and added an option -n to set the name of the project. If you do not specify the name it will be automatically set to the equivalent name of the folder. You can also use command dotnet new -l to get a list of all available templates. After running this command, if you open the folder you will see a newly created solution. Related to the project standard structure, create a new folder near the solution in any way:

Enter into this new directory and create the project with the command

Option “mvc” means that the project type will be “ASP.NET Core Web App (Model-View-Controller)” and the name will be set to the folder name. To link the solution and the project return back to the solution folder and run next command:

dotnet sln add .\CoreAppProj\CoreAppProj.csproj

If you now open the project in the Visual Studio you will see a standard created project:

If you review the project files carefully, you will notice, that the .csproj file format has been simplified in ASP.NET Core. Let us review the main changes step by step.

Program.cs

In ASP.NET Core, the entry point to an application is Startup.cs, and you no longer have a dependency on Global.asax. ASP.NET Core handles the entry through the Program.cs Main method (similar to console applications and ASP.NET Core application is actually a console application) and Startup is loaded through there:

        public static void Main(string[] args)
        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>();

The “Main” method uses WebHostBuilder, which follows the builder pattern, to create a web application host. The builder includes:

As we mentioned above, the default server should be Kestrel and you often can meet the following realization:

        public static void Main(string[] args)
            var host = new WebHostBuilder()
                .UseKestrel()
                .Build();
            host.Run();

Both of them (realization above and in our example) is good, you just need to know that using “CreateDefaultBuilder” method means that next default settings will be applied (provided by official Microsoft documentation):

You can manually change the parameters and set another web server. The Build and Run methods build the IWebHost that will host the app and start it listening for incoming HTTP requests.

Startup.cs

The UseStartup method on WebHostBuilder defines the Startup class of the application, where application’s request pipeline is defined and where all services are configured. A startup must include a Configure method, where the necessary middleware is added to the pipeline. The below is shown the generated piece of code, which you should see after creating a project:

        public Startup(IConfiguration configuration)
        public IConfiguration Configuration { get; }
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
            services.Configure<CookiePolicyOptions>(options =>
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
                app.UseExceptionHandler(“/Home/Error”);
            app.UseCookiePolicy();
                    name: “default”,
                    template: “{controller=Home}/{action=Index}/{id?}”);

ConfigureServices defines the services used by the application and Configure defines the middleware in the request pipeline. In the example above, Configure method configures the pipeline with support for:

ASP.NET Core middlewares are pieces of code which perform asynchronous logic on an HttpContext. Incoming requests are passed through the pipeline, where each middleware invokes the next middleware in the pipeline or terminates the request. Middleware can perform any kind of operations, such as handling authentication, errors, static files, etc. For example, MVC in ASP.NET Core is also implemented as middleware. Actually, you can either create custom middleware or use needed one from a huge set of built-in middleware, and you can write your own custom middleware. In the example above the middlewares are:

Configuration

As mentioned before, ASP.NET Core also changed its configuration model for handling simple name-value pairs. The new configuration model is based on key-value pairs established by configuration providers instead of relying on System.Configuration or web.config. Configuration providers can read configuration data from a difference of file formats: XML, JSON, INI formats, as well as from environment variables, command line arguments or an in-memory collection. You can also write your own custom configuration provider. By default, in your test project, which we created above, you should see automatically created JSON file with a name “appsettings.json”. In it, you can add connection string, set allowed hosts and so on.

Environment Variables Configuration Provider

New configuration model also allows using environment variables via EnvironmentVariablesConfigurationProvider, which loads configuration from environment variable key-value pairs at runtime. To activate the environment variables configuration, you should add call the AddEnvironmentVariables extension method on an instance of ConfigurationBuilder. To activate the environment variables configuration, you should add call the AddEnvironmentVariables extension method on an instance of ConfigurationBuilder. When the application will be run, the Environment Variables Configuration Provider will be called right after configuration is established from user secrets and appsettings files. Calling the provider in this position allows the environment variables to read at runtime to override configuration set by user secrets and appsettings files.

Running the Application

At the beginning of the section, we have already briefly reviewed the ways to start the development of applications by use of .NET Core CLI tools, so, now you must have a project, for which we will review few more commands to finish this rough overview tutorial.
If you start looking for any information about running an application via CLI, you can find at least 3 commands:

Actually, if you are using the .NET Core 2.0 SDK, when you will need to use only the last command from this list. dotnet restore command runs implicitly by all commands that require a restore to occur: dotnet new, dotnet build and dotnet run. This command is still being used in certain cases, but in this particular one it is not required. As for the dotnet build – it is also called by the command dotnet restore to ensure that the build targets have been built. That is why, if we run command dotnet run the project dependencies are downloaded, the project is build and the application runs. And that is all! Now, you can start using these basic concepts to create an application and improve your skills.

Conclusion

.NET Core and ASP.NET Core include many new enhancements, fundamental changes that should help you in everyday development. Can you imagine, if in the past someone said Microsoft would provide open source and cross-platform solutions? Probably, most of us would have said it would never happen. However, times change and today Microsoft provides really great solutions, which attract more and more developers. That is why we believe that what the future holds is even more epic changes about which we will write another article.

This content was originally published here.