ASP.NET Core 2.2 For Beginners (Part 1): Your First ASP.NET Core Application

If you haven’t already installed Visual Studio 2019 version 16.0.0. version or later, you can download a free copy here: www.visualstudio.com/downloads.

Now that you have Visual Studio 2019 installed on your computer, it’s time to create your first solution and project.

  1. Start Visual Studio 2019 and click the Create a new project button (image below the bullet list).
  2. Select NET Core Web Application in the template list and click the Next button. You can type Web in the search bar to filter the available templates (see image below).
  3. In the Configure your new project dialog:
    1. Name the project AspNetCore22Intro in the Name
    2. Select a folder for the solution in the Location
    3. Name the solution AspNetCore22Intro in the Solution name
    4. Make sure that the Create directory for solution checkbox is checked.
    5. Click the Create
  4. In the project template dialog:
    1. Select.NET Core andNET Core 2.2. in the two drop-downs.
    2. Select Empty in the template list.
    3. Click the OK button in the wizard dialog.
  5. When the solution has been created in the folder you selected, it will contain all the files in the AspNetCore22Intro
  6. Press Ctrl+F5 on the keyboard, or select Debug-Start Without Debugging in the main menu, to run the application in the browser.
  7. Note that the application only can do one thing right now, and that is to display the text Hello World! Later in this, and the next, module you will learn why that is, and how you can change that behavior.

 

For now, just note that the application is running on localhost:44385 (the port number might be different on your machine).

If you right click on the IIS icon in the system tray, you can see that ISS is hosting the AspNetCore22Intro application.

The Project Layout and the File System

There is a direct correlation between the files in the solution folder and what is displayed in the Solution Explorer in Visual Studio. To demonstrate this, you will add a file to the file structure in the File Explorer and see it show up in the Solution Explorer in real-time.

  1. Right click on the AspNetCore22Intro solution node in the Solution Explorer and select Open Folder in File Explorer.
  2. When the File Explorer has opened, you can see that the solution file sln is in that folder, along with the project folder with the same name.
  3. Double click on the project folder in the File Explorer to open it.
  4. Right click in the File Explorer window and select New-Text Document and press Enter on the keyboard.
  5. A new file with the name New Text File should have been created in the folder.
  6. Now look in the Solution Explorer in Visual Studio; the same file should be available there.
  7. Double click the icon for the New Text File document in the Solution Explorer in Visual Studio, to open it.
  8. Write the text Some text from Visual Studio in the document and save it.
  9. Now switch back to the File Explorer and open the file. It should contain the text you added.
  10. Change the text to Some text from Notepad using the text editor (not in Visual Studio) and save the file.
  11. Switch back to Visual Studio; the altered text should now be displayed in the document.
  12. Close the text document in Visual Studio and in the text editor.
  13. Right click on the file in the Solution Explorer in Visual Studio and select Delete to remove the file permanently.
  14. Go to the File Explorer and verify that the file was deleted from the folder structure.

As you can see, the files in the project are in sync with the files in the file system, in real-time.

Important Files

There are a couple of files that you need to be aware of in ASP.NET Core 2.2, and these have changed from the 1.0 version.

The Properties folder in the Solution Explorer contains a file called launchSettings.json, which contains all the settings needed to launch the application. It contains IIS settings, as well as project settings, such as environment variables and the application URL.

One major change from ASP.NET Core 1.0 is that the project.json file no longer exists; instead the installed NuGet packages are listed in the .csproj file. It can be opened and edited directly from Visual Studio (which is another change) or its content can be changed using the NuGet Package Manager.

To open the .csproj file, you simply right click on the project node in the Solution Explorer and select Edit AspNetCore22Intro.csproj (substitute AspNetCore22Intro with the name of the project you are in).

You can add NuGet packages by adding PackageReference nodes to the file .csproj, or by opening the NuGet Package Manager. Right click on the project node or the Dependencies node, and select Manage NuGet Packages to open the NuGet Manager.

One change from the ASP.NET Core 1.1 version is that there now only is one main NuGet package called Microsoft.AspNetCore.App that is installed when the project is created. It contains references to the most frequently used NuGet packages, the ones that you had to add separately in the 1.1 version.

Open the .csproj file and the NuGet manager side by side and compare them. As you can see, the same package is listed in the dialog and in the file.

You will be adding more NuGet packages (frameworks) as you build the projects.

Compiling the Solution

It is important to know that ASP.NET will monitor the file system and recompile the appli­cation when files are changed and saved. Because ASP.NET monitors the file system and recompiles the code, you can use any text editor you like, such as Visual Studio Code, when building your applications. You are no longer bound to Visual Studio; all you need to do is to get the application running in the web server (IIS). Let’s illustrate it with an example.

  1. Start the application without debugging (Ctrl+F5) to get it running in IIS, if it isn’t already open in a browser.
  2. Open the cs file with Notepad (or any text editor) outside of Visual Studio. This file is responsible for configuring your application when it starts.
  3. Locate the line of code with the string Hello World. This line of code is responsible for responding to every HTTP request in your application.

await context.Response.WriteAsync("Hello World!");

  1. Change the text to Hello, from My World! and save the file.

await context.Response.WriteAsync("Hello, from My World!");

  1. Build the solution (Ctrl+Shift+B) in Visual Studio without closing the browser and then refresh the application in the browser. You need to build the solution because the C# code needs compiling. Changes to CSS and HTML don’t require a build, just refresh the browser.
  2. The text should change from Hello World! To Hello, from My World!
    The reason this works is because ASP.NET monitors the file system.

 

You can create cross-platform applications using ASP.NET Core 2.2, but this requires the .NET Core template. As of this writing, this template has limitations compared with the .NET Framework template, but big changes are coming in ASP.NET Core 3.0. So, if you don’t need the added features in .NET Framework, then use the .NET Core template, as it is much leaner and cross-platform ready.

The Startup.cs File

Gone are the days when the web.config file ruled the configuration universe. Now the Startup.cs file contains a Startup class, which ASP.NET will look for by convention. The application and its configuration sources are configured in that class.

The Configure and ConfigureServices methods in the Startup class handle most of the application configuration. The HTTP processing pipeline is created in the Configure method, located at the end of the class. The pipeline defines how the application responds to requests; by default, the only thing it can do is to print Hello World! to the browser.

If you want to change this behavior, you will have to add additional code to the pipeline in this method. If you for instance want to handle route requests in an ASP.NET MVC appli­cation, you have to modify the pipeline.

In the Configure method, you set up the HTTP request pipeline (the middleware) that is called when the application starts. In the second part of this book, you will add an object-to-object mapper called AutoMapper to this method. AutoMapper transforms objects from one type to another.

The ConfigureServices method is where you set up the services, such as MVC. You can also register your own services and make them ready for Dependency Injection (DI); for instance, the service that you implement using the IMessageService interface at the beginning of the book.

You will learn more about how to configure your application in the next chapter.

For now, all you need to know about dependency injection is that, instead of creating in­stances of a class explicitly, they can be handed to a component when asked for. This makes your application loosely coupled and flexible.

Adding a Configuration Service

Let’s say that the hard-coded string Hello, from My World is a string that shouldn’t be hardcoded, and you want to read it from a configuration source. The source is irrelevant; it could be a JSON file, a database, a web service, or some other source. To solve this, you could implement a configuration service that fetches the value when asked.

Let’s implement this scenario in your application

  1. Open the json file.
  2. As you can see, some default logging settings already are in the file along with host settings. Add the following key-value pair: “Message”:”Hello, from configuration” below the AllowedHosts property and save the file.

"Message": "Hello, from configuration"

  1. To read configuration information from the json file, you have to add a constructor to the Startup class. You can do that by typing ctor and hitting the Tab key twice in the class.

public class Startup
{
    public Startup()
    {
    }
    ...
}

  1. Use Dependency Injection (DI) to inject the IConfiguration service into the constructor and store the service object in a class-level read-only property named Configuration. To get access to the service interface, you have to resolve the Extensions.Configuration namespace by adding a using statement for it.

public IConfiguration Configuration { get; }
public Startup(IConfiguration configuration)
{
    Configuration = configuration;
}

  1. To replace the hardcoded text Hello, from My World! with the value stored in the Message property in the json file, you have to index into the Configuration property. Store the value in a variable in the Configure method above the WriteAsync method call.

var message = Configuration["Message"];

  1. Now, replace the hardcoded text with the variable.

await context.Response.WriteAsync(message);

  1. Save all the files and go to the browser. Refresh the application to see the new message.

The Startup class’s code, so far:

public class Startup
{
    public IConfiguration Configuration { get; }

    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public void ConfigureServices(IServiceCollection services)
    {
    }

    public void Configure(IApplicationBuilder app,
    IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.Run(async (context) =>
        {
            var message = Configuration["Message"];
            await context.Response.WriteAsync(message);
        });
    }
}

Stay connected with news and updates!

Join our mailing list to receive the latest news and updates from our team.
Don't worry, your information will not be shared.

Subscribe
Close

50% Complete

Two Step

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.