Building .NET Core Basic Application With Visual Studio 2017 - Day Two

EIn the previous article of this series, we discussed why .NET Core was introduced by Microsoft and also what are the main advantages of it. In the previous article, we also learned how to create a console Application in .NET Core, using command line argument. If you want to look at the previous articles of this series, please visit the links given below.

Even if using the command line may sound intriguing to you, it’s not the best way to write the code — especially when we need to write the complex Applications. This is partially due to the fact that if we don’t have a proper IDE to code against, we are stripped of all the awesome features that Visual Studio provides such as IntelliSense, the Debugger, the Immediate Windows and so on.

Luckily for us, there is a way to solve this. If you have previously installed the new Visual Studio 2017 tools, you may have noticed during your daily fights inside Visual Studio’s dungeons, which are under .NET Core node and you have the new project templates.

They respectively allow you to create a console Application, which can run on .NET Framework, .NET Core and a Class library, which can target any framework. Let’s create a new Console Application (.NET Core) and see where we can go from there.

The process of creating a new project does not change. We are using Visual Studio. Once the project is created and Visual Studio has finished loading, our solution looks, as shown below. 

 
  1. First we need to open Visual Studio 2017.
  2. Now, click on New Project button.


Select Empty Project Type from the New Dialog Box and click OK button.
 
 

Looking at the Solution Explorer, notice that the folder structure and the files are very different from the previous version of ASP.NET. First of all, there is a wwwroot folder, which contains all the static files. As we can see, the solution’s structure differs little from what we are used to seeing. The first thing which we notice is that we use the new special files global.json and project.json. The project.json file contains all the information that the CLI needs to run your project. The global.json file is used to configure all the projects within a directory. It includes just two default sections- the projects section and the SDK section. The projects property designates which folders contain source code for the solution. By default, the project structure places the source files in a src folder.

In a different section, we will explain how to use wwwroot folder and the reason why you need it.

All the files in the root of the project are either the new additions or they changed their role

  • Program.cs is the entry point for the Web Application; everything starts from here. As we mentioned in the chapters before, .NET Core host can only run console Applications. Thus, the Web app is a console Application too.
  • project.csproj is an XML-based project configuration file. It contains all the package references and the build configuration.
  • Startup.cs is not exactly new. If you already used OWIN, you probably know the role of this class, but we can definitely say if the Program.cs is the entry point of the .NET Core app, Startup.cs is the entry point of ASP.NET Core Application (previously we were using the global.asax file).
  • web.config is still here, but it's almost empty and only used to tell Internet Information Service (IIS) to process all the requests, using ASP.NET Core handler.

Program.cs

As mentioned before, this class is the entry point of .NET Core Application and its role is to create the host for the Web Application. Since we can host our Web Application on different Web Servers with .NET Core, this is the right place to configure everything.

Startup.cs

The ASP.NET Core pipeline starts here. As you can see from the code given below, almost nothing comes with the template. What’s important here are the methods ConfigureServices, where Dependency Injection is configured (we’ll talk about this later in the chapter) and configure, where all needed middleware components are registered and configured. It is app.Run method, which is a perfect example of an inline middleware component. In this case, it is useless because the Web Application will always return the text string "Hello World!", but more complex logic (i.e. authentication, monitoring, exception handling and so on) can be added.

Startup class

Startup class is absolutely the most important class in your Application because it defines the pipeline of your Web Application and it registers all the needed middleware components. Because of this, it might be very complex with lots of lines of code. If you add checking for the environment, everything can be more complicated and difficult to read and maintain. For this reason, ASP.NET Core allows you to use different startup classes- one for each environment; you want to manage or one for different "configure" methods. The method .UseStartup<Startup>() is very clever. It can switch between different classes automatically, if you are following the right convention (method name + environment name). For example, if you duplicate the Startup class and rename it StartupDevelopment, the extension method will automatically use the new one in the development environment. You can use the same convention for the Startup class methods. Hence, duplicate the method Configure of the Startup.cs file, call it ConfigureDevelopment and it will be called instead of the original one only in the development environment.

Now, open the program.cs file and overwrite the code with the code 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. using Microsoft.AspNetCore.Builder;     
  8. using Microsoft.AspNetCore.Http;  
  9.   
  10. namespace Prog1_Intro  
  11. {  
  12.     public class Program  
  13.     {  
  14.         public static void Main(string[] args)  
  15.         {  
  16.             var host = new WebHostBuilder()  
  17.                 .UseKestrel()  
  18.                 .UseContentRoot(Directory.GetCurrentDirectory())  
  19.                 .UseIISIntegration()  
  20.                 .UseStartup<Startup>()  
  21.                 .UseApplicationInsights()  
  22.                 .Build();  
  23.   
  24.             host.Run();  
  25.         }  
  26.     }  
  27. }  
Similarly, now open the startup.cs file and replace the code with the code given below.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Threading.Tasks;  
  5. using Microsoft.AspNetCore.Builder;  
  6. using Microsoft.AspNetCore.Hosting;  
  7. using Microsoft.AspNetCore.Http;  
  8. using Microsoft.Extensions.DependencyInjection;  
  9. using Microsoft.Extensions.Logging;  
  10.   
  11. namespace Prog1_Intro  
  12. {  
  13.     public class Startup  
  14.     {  
  15.         public void ConfigureServices(IServiceCollection services)  
  16.         {  
  17.         }  
  18.   
  19.   
  20.         public void Configure(IApplicationBuilder app)  
  21.         {  
  22.             app.Run(  
  23.                 context =>  
  24.                 {  
  25.                     return context.Response.WriteAsync("First Web App in .Net Core");  
  26.                 }  
  27.                 );  
  28.         }  
  29.     }  
  30. }  

The Configure method

The Configure method is used to specify how ASP.NET Application will respond to HTTP requests. The request pipeline is configured by adding middleware components to an IApplicationBuilder instance, which is provided by Dependency Injection.

The ConfigureServices method

The ConfigureServices method is optional; but if used, it's called before the Configure method by the runtime (some features are added before they're wired up to the request pipeline). For the features that require substantial setup, there are Add[Service] extension methods on IServiceCollection. This example from the default web site template configures the app to use the Services for an Entity Framework, Identity and MVC:

Services Available in Startup

ASP.NET Core Dependency Injection provides Application Services during an Application's startup. You can request these Services by including the appropriate interface as a parameter on your Startup class's constructor or one of its Configure or ConfigureServices methods.

Looking at each method in the Startup class in the order in which they are called, the Services given below may be requested, as the parameters.

  • In the constructor: IHostingEnvironment, ILoggerFactory.
  • In the ConfigureServices method: IServiceCollection.
  • In the Configure method: IApplicationBuilder, IHostingEnvironment, ILoggerFactory, IApplicationLifetime. 
Now, run this console Application and the output will be, as shown below.



You can read the next part here,


Similar Articles