gswardman

.Net Core: Tutorial for Beginners

By gswardman August 19, 2022

Microsoft’s .NET core platform is used to develop both complex and simple solutions running on the cloud, mobile, IoT devices, all computer platforms and pretty much every other architecture out there. As a developer, you are likely going to interact with it in some way even when you are using other technologies to develop.

In this tutorial, we provide a quick and easy-to-digest overview of .NET Core from a developer perspective. It should serve as a resource for both beginners and senior devs who want to get into .NET development but have little time to go through lengthy documentation.

Table of Contents

What Is .NET Core?

.NET Core – pronounced as dotnet core- is an open-source, general-purpose, software development platform developed by Microsoft. It was first released in 2016 alongside Visual Studio 2015 as a versatile cross-platform alternative to .NET Framework. Its popularity has shot up in recent years coming third in the 2021 Stackoverflow developer survey -other frameworks and libraries category.

The main characteristics of .NET Core and its successor .NET 5 from a developer perspective include:

 .NET Core is Cross Platform

Unlike many of Microsoft’s previous development frameworks and tools, .NET core was created as a cross-platform development platform. This means you can run it on Windows, Mac OS, and Linux, and the software you develop can be run on all three platforms. You can also use the platform to develop and test mobile applications, microservices, web applications, etc.

.NET being cross-platform also means that developers can use essential Microsoft development tools on all platforms.  For instance, there are Mac and Linux versions of Visual Studio- Microsoft’s popular IDE. The same goes for the CLI, libraries, mobile dev tools, and server development architecture.

.NET Core was a departure from previous development frameworks that were fragmented and native to Windows. Microsoft, on the release of this new platform, said that they aimed for NET to become a versatile dev platform with a single code base that would allow all developers to build solutions for all OS platforms.

.NET Core is Open Source

Microsoft chose to open source .NET core and its subsequent versions because they understood the importance of having a community around it and the growing need for transparency. For these reasons, .NET Core’s codebase is available as an open package on Github published under the Apache 2 and MIT licenses.

NET Core’s runtime source code, its SDK repo, the Rosyln language compiler, and ASP.NET Core repository source codes are available on the Github project page managed by the .NET foundation. The implications from a developer perspective are that anyone can contribute to changes, participate in code reviews, and access all design documents relating to the entire .NET Core framework.

Microsoft says that open sourcing their entire development platform has had many positive implications like making the product attractive to developers and enabling faster implementation. It also makes it easy for both new and experienced developers to understand how .NET Core works and its overall direction as a development platform.

Cross-Architecture Uniformity

A developer working on solutions in any architecture (x64, x 86, or ARM) can execute uniformly across all of them and expect the same behavior from their app. This is a great improvement from previous development environments that required a lot of work to port solutions across architecture and, often, it led to inconsistent behavior and bugs that had to be addressed with updates.

Deployment Flexibility

Unlike previous dev environments by Microsoft, .NET Core allows flexible code deployment on top of the framework or as a self-contained, independent deployment. Deploying on top of the framework means the app is lightweight and relies on natively installed .NET Core deployment components. On the other hand, an independent or standalone deployment allows you to pack every single .NET deployment component within your app bundle.

Backward and Horizontal Compatibility

.NET Core and its successor maintain very good backward compatibility with the old .NET framework as well as horizontal compatibility with other frameworks such as Xamarin and Mono. Implementing components or functionality from these frameworks is smooth and transparent.

Fully-Featured Command Line interface

Fully-Featured Command Line interface

In line with other popular and modern software development platforms like Node, .NET Core came with a very powerful CLI toolset you can use to install packages/dependencies, build, test, execute, and deploy .NET Core applications. The CLI is also cross-platform and open source like the rest of the platform and comes bundled with the .NET Core install.

It is a Modular Development Platform

One of the biggest complaints developers had with the old .NET framework was how heavy it was because it came as a single package mostly full of unwanted components. To improve on that, Microsoft decided to make .NET Core modular. The platform is delivered in an agile fashion using a set of independent and fine-grained NuGet packages.

As a developer, this modularity allows you to update or deploy only the packages and components that are relevant to your project. NET Core consists of the .NET runtime (CoreCLR), the SDK and compiler, the .NET app host, and the fundamental libraries. Nuget assembly packages are spread across the entire development platform and can be removed or integrated at will depending on the nature of the project or desired dev environment.

Setting Up .NET Core

ASP .net core leverages the provider model, a convenient design pattern, to load configuration value/key pairs from different sources while exposing them to developers as one configuration object. This allows them to grasp a configuration key such as ConnectionString with a single line of code regardless of source. The configuration API in .net core console applications isn’t available by default. Here are the Nuget packages to obtain the Configuration API and initiate the providers as ASP core web page apps.

Design a .Net Core Console Application

Access .Net core via Visual Studio 2017, then navigate to Console Application and change its name to, for example, “myconsolecore application.” incorporate a JSON configuration file (appsettings.json) as the premier configuration keys source. Ensure the “Copy to Output Directory” is configured to “copy always” for the newly incorporated JSON file to facilitate its publication with the application. Replace the appsettings.json file with:

hey

Doing so configures the property “message” to the “Hey” value.

Write Code

Before updating the application, include the Nuget package (install-package Microsoft.Extensions.Configuration.Json) with the provider necessary for loading JSON configuration files. Replace the core method contents with static Main void string:

main void

This loads the appsettings.json file in the configuration object and removes each value and property. Suppose your defined property (Message) is configured to the value of “Hey from appsettings.json.” The WritrLine procedure will exhibit the Message property’s value on the console window. Running the application generates the “you have loaded configuration data successfully from the appsettings.json file.”

Incorporate Environment Variables

You can do so by installing the Nuget Package below:

Install-package Microsoft.Extensions.Configuration.EnvironmentVariables

Now update the Core method to incorporate the provider, as seen below.

addjson

This loads environment variables in the configuration item and facilitates container or cross-platform deployments. Further, since environment variables are installed after the appsettings.json file, possible duplicate keys replace the values from the appsettings.json file.

Include the “Message” environment variable to counter the Message property from the Project Properties section in appsettings.json. Some developers replace the initially configured Message key in the appsettings.json file with environment variable contents.

Include Command Line Arguments

Add the Command Line Arguments configuration provider. The first step involves installing the right Nuget package.

Install-Package Microsoft.Configuration.Extensions.CommandLine

Load the new provider by updating the Core method, as seen below.

iconfig

Incorporate a command line argument to amend the project properties. This will replace the Message property with the “Hello from args” string. The “Message” property was configured three times: in the appsettings.json file, as an environment variable, and as a command line argument. The final loaded provider conquers possible conflicts.

.Net core incorporated a flexible and robust configuration API in the ASP Core application by default. Adding some Nuget packages to a .Net Core application provides similar flexibility. The chronology of adding the configuration builder is crucial because the last incorporated counters previous values. Applying this in the above-mentioned order gives you a configuration environment similar to what’s available in ASP core applications.

Installing .NET Core SDK

.NET comprises the SDK and the runtime. The SDK facilitates the creation of .NET libraries and applications, while the runtime helps run a .NET application. There are two forms of supported releases.

The standard term support (STS) or long-term support (LTS). While these releases have the same quality, the length of support is different. LTS releases acquire free patches and support for three years, while STS gets the same for 18 months. You can install .NET core SDK via the Windows package manager with the winget tool.

When installing .NET system-wide, consider installing it with administrative privileges. Developers can leverage .NET SDK to create applications with .NET. After installing the .NET SDK, you won’t have to install the comparable runtimes. Run the Windows command prompt below to install .NET SDK.

.net sdk

Creating a New Project in .NET Core

Developers can use .NET core to create IoT, cloud, and web applications on a cross-platform environment like Linux, MacOS, and Windows. ASP.NET core also facilitates the hosting applications on modern platforms like AKS and docker.

This framework comes with inbuilt features like dependency injection. What’s more, you can enable swagger, containerization, and docker in one click. Here is a guideline to help you develop an ASP.NET core MVC web application.

Step 1: Launch Open Visual Studio

When Visual Studio launches, click “Continue Without Code.”

Proceed to the Visual Studio Menu and click on “File” then “New Project.”

Click on the “New Project” option.

Step 2: Select the Project Template

You can select any of the following project templates.

ASP.NET Core Web App (Model-View-Controller): Do you want your web application to feature Model, View, Controller? This template will be ideal.

ASP.NET Core Web App: Developers planning to create web applications with Razor pages but without Model, View, Controller should use this template.

In this case, the developer chose the ASP.NET Core Web App (Model, View, Controller) template.

Step 3: Describe the Name of Your Project and its Location

Launch the project configuration window to reveal the options below.

Project name: Write your preferred project name

Location: Choose where the project files will be saved on your computer’s hard drive

Solution name: This is an auto-defined option based on your project name. Change it accordingly. You can also define the available checkbox, as seen below. Once you do so, the project files and solution file will be saved in that folder.

config new project

Step 4 – Define the Target Framework

Select the latest target framework. Here, we’ll use .NET 5, but you can still pick any other, depending on your needs. Skip the additional details, then click the create option to create your ASP.NET Core MVC web application.

Understanding the Project Structure

Here is the default structure of your project.

The wwwroot Folder

The default wwwroot folder stores static files related to your project. You can access these files programmatically through a relative path.

The Controller Folder

This folder comprises the controller sets where you write operation-based code.

The Model Folder

Here you will find the entity or domain group. You can write models in different sections of the solution, like a folder or class library.

The Views Folder

This folder contains the razor pages that facilitate user data display and acquisition.

The appsettings.json File

In this folder, you will find the secret and configuration details of your application.

Program.cs File

This marks the application’s starting point. It also creates the host enabling an application to run the app.

Startup.cs File

Leverage the Startup.cs file to set up the behavior of the application. For example, you can define the dependency injection and routes.

Developing Applications with .NET Core

When developing hybrid applications, web services, or mobile backends, developers can use the ASP.NET Core. This framework helps you create feature-dense applications to solve different problems. Let’s discuss how to develop a web application using ASP.Net.

Creating a Web Application with ASP.NET Core

To create a web application, you’ll need Open Visual Studio 2019. Click the Create a new project box option to launch the “Create a new project” window.

In that window are various .NET Core 3.1 application templates. Are you a beginner who wants to develop a simple application? Select the ASP.NET Core web application template > click next. That will reveal the “Configure your new project” window, where you can choose your project name and define where you will develop your application.

Under the solution name for your application, give it your preferred name. For example, “beginnercorewebapplication.”

Now click create to launch the “Create a new ASP.NET Core web application” option. Select the suitable ASP.Core Web application template. The options here are; web application, API, Empty, Angular, or Web Application (MVC). Our developer here chose the empty template. Remember to choose the suitable ASP.Net Core and .NET core versions.

Uncheck the checkboxes under the Advanced section and click the create option to create a new .NET core web application in Open Visual Studio 2019. Allow Visual Studio to restore packages in the project. During the restoring process, Visual Studio will automatically add, update, and delete any configured dependencies like NuGet packages in the application.

Below is the application’s folder and file structure.

Run the .NET Core Application

To run this application, you can either press Ctrl + F5 without Debug or F5 with Debug. You can opt to click IIS Express. Either of these options will launch the browser and display the output below.

.NET Core Application

The “Hello World” output is from the Configure technique of the Startup class, which is available in the Startup.cs file Open Startup.cs file. You’ll need to change the “Hello World” output before rerunning the application.

Project Templates in ASP.NET Core Application

Developers can use different templates when creating their .NET core web applications. Let’s discuss them in detail below.

Empty Project Template

This project template is, as the name suggests, empty. Choose this template if you’re a DIY developer who prefers doing everything from scratch.

Web Application (Model-View-Controller) Template

Do you want a template with everything you need to develop a .NET Core MVC Web Application? Besides creating Models, Views, and Controller folders, this template incorporates web-specific components like Layout files, CSS files, and JavaScript. These components facilitate the development of a web application.

API Template

If you want to create an ASP.NET Core RESTful HTTP service, select the API template. While it features the Controllers folder, other web-specific components like view, JavaScript, CSS, and layout files are mission. Why is that so? It’s because an API doesn’t feature any user interface. The views and models folders are also missing in the API template because they aren’t necessary for an API.

Web Application Template

This template leverages the new Razor Pages framework for developing web applications. Developers can use new Razor pages to ease and enhance the productivity of page-focused scenarios. Suppose you want to create a web application without the entire complexity of ASP.NET MVC. This template should be your go-to option.

Angular, React.js, React.js, and Redux

You can develop an ASP.Net core web app jointly with Redux and React, React, or Angular.

Creating a Console Application with .NET Core

In this project, we’ll use .NET 6, a highly improved framework regarding code quality, security, and performance. It offers one of the smoothest developer experiences and long-term support. Are you a beginner in the development world? Begin your .NET learning process with Visual Studio IDE and an advanced framework. Here is a guideline to help you develop a console application using .NET 6 and .NET 5.

Step 1: Launch Visual Studio 2022 and click “Create a new project”

Visual Studio 2022

Step 2: Click “Console App,” then click “Next.”

Console App

Step 3: Define the project name and its location

configure new project

Step 4: Choose framework: .NET 6.0 (Long-term support)

additional information

This will reveal the console app, as seen below.

firstconsoleApp

Here is the default Program.cs file. You can also see the project.csproj file

// See https://aka.ms/new-console-template for more information Console.WriteLine(“Hello, World!”);

information Console

Click “Start without debugging” to compile and run the program. If you love quick fixes, you can also press Ctrl+F5.

The “FirstConsoleApp.exe” will appear in the defined folder location of your project. You can run the .exe file, which shows the “Hello, World” prompt.

Creating the Project with .NET 5

Follow the above steps apart from step 4, where you should choose .Net 5.

The Program.cs of the console app with .NET 5 is as you can see below.

Creating the Project with .NET 5

.NET6 vs. .NET 5

The Program.cs of .NET 5 features; Using the system, Main method, and Namespace

class keyword. These options are unavailable in .NET 6.

Developers can extend their .NET 6 console applications by incorporating a new class. Here is the procedure.

Right-click the project, click add to reveal Class, then click ass.

install

Give your class a suitable name. You want to create a public void method – Sum in your class.

Use the following code:

public void

The detailed code of your class.cs is;

namespace FirstConsoleApp { internal class Class1 { public void Sum() { int a = 5; int b = 6; int Sum = a + b; Console.WriteLine(“Sum : {0}”, Sum); } } }

If you’ve not yet noticed, this class contains:

  • The namespace
  • Using statements (by default)
  • Internal Class

Program.cs doesn’t come with these features.

Understanding the Call Sum() Method

In Program.cs class, you will call the sum method of your class.cs. Here, you’ll need to add namespace: with FirstConsoleApp using the code below.

using FirstConsoleApp; //need to call method from Class1 Class1 class1 = new Class1(); class1.Sum();

Should you run the app now, you’ll get Sum:11 in the console.

The detailed Program.cs code is:

Program.cs code

Creating a desktop application with .NET Core

The tools below are necessary for developing a web application using .NET Core. You need some basic understanding of C# and .NET development. Developers can use C# to build application samples.

  • SQL Server 2008 Express Edition
  • Visual Studio 2019 Community Edition
  • SQL Server Management Studio

Developers can download these tools free of charge. Let’s create this application with the .NET framework version 4.7.2.

Step 1: Build the Data Source

This is the location where you’ll be saving all your data. You can name it based on your preferences, but in our case, we’ll call it “EmployeeDB” and incorporate an “Employee” table, as shown in the image below.

The “Employee_ID section will be the identity field where you store the unique key value for your employee records. Your complete Employee table should appear as seen below.

Build the Data Source

Now, add one record to your table. Below is an example.

Your data store is now complete.

data store

The Data Access Layer

Start your project by building a solution, which you can call “EmployeeDesktop.” This project will host the “Employee” class, where employee records are stored. You must keep the class in a separate project. You’ll use it independently from your data access project across multiple projects.

Your complete employee class will appear as follows.

Data Access Layer

This image displays the “Employee” table in the database.

Now build the data access layer project. You’ll need to incorporate a new project, in this case, “EmployeeDAL” into the solution.

Once your project is ready, add the “EmployeeDAL” class and “IEmployeeDAL” interface. Doing so will complete your data access layer plus its related components. Now part of your solution is ready. It will help you read data from the data store and keep it in a .NET class matching the records in the data store.

Creating the Business Logic Layer

In this next project, you’ll build the business logic layer, which we’ll call the “EmployeeBL.” It will host the “IEmployeeBL” interface and the “EmployeeBL” class responsible for implementing the interface. Further, you’ll build a new class, “Employee” into a new project called the “EmployeeUI.”

This is the employee category that will appear on the user interface. The business logic layer reads data from the data access layer. It then applies business logic before displaying it on the front end. Suppose you’re a beginner, the examples below can be a good starting point.

It’s not complex; you will need to add an employee’s first and last name to get their name. Input the address details to fetch the address and use the birth value read data from the database to display the employee’s age.

At this point, you’ve created three main components of your solution. You have the data store, data access layer, and business logic layer. Let’s proceed to the next step of the project.

The Presentation Layer or Front End

This part marks the final stages of your project. Here, you will display the data you have read from the data store, and converted into the user’s preferred format.

Presentation Layer or Front End

Presentation Layer or Front End

Presentation Layer or Front End

At this point, you’ve created three main components of your solution. You have the data store, data access layer, and business logic layer. Let’s proceed to the next step of the project.

The Presentation Layer or Front End

This part marks the final stages of your project. Here, you will display the data you have read from the data store, and converted into the user’s preferred format. Fo this application you’ll be using a Windows Presentation Foundation (WPF) application with the MVVM design pattern.

You can get comprehensive details about the pattern from online sources. The final step involves creating an “EmployeeFrontEndApp” WPF application, containing the “EmployeeDetails.xaml” view, plus the “EmployeeDetailsVM.cs” view model, as shown in the images below.

The Presentation Layer or Front End

Presentation Layer

To complete the process, incorporate the Employee view in the Main Window, as seen in the image below.

Main Window

Here is the completed structure of your solution.

completed structure of your solution

Time to develop and run the application, as seen below.

develop and run the application

There you have your complete functional .NET desktop application, covering all architecture layers. You can expand it to incorporate new features. For example, adding a new employee. You can also delete an employee who no longer works for the company from the data source.

Creating a Mobile Application with Xamarin

Start by selecting your preferred development environment. You can opt for:

  • Visual Studio 2019
  • Visual Studio 2022
  • Visual Studio for Mac

Use this sample to ease the process, alongside the following steps.

Select file, click new and navigate to project. You can also click on “Create new project” option.

Find “Xamarin, or navigate to the Project type menu and select Mobile. Choose the Mobile App (Xamarin.Forms) project type.

Select your preferred project name.

Click the “Blank” project type and check iOS and Android.

Wait for the NuGet packages to restore. You’ll get a “Restore completed” alert in the status bar.

Here are some points to remember when executing this project.

If you’re using the New Visual Studio 2022, chances are the Android SDKs won’t be installed. You may get a prompt to install a more recent Android SDK.

New Visual Studio 2022 installations aren’t configured with an Android emulator. To create the Android Emulator, click on the dropdown menu below to activate the emulator creation screen.

dropdown menu

Choose the default settings from the emulator creation screen, then click the create option.

After creating the emulator, the system will take you back to the “Device Manager” window. Visual Studio 2022 will now display the new emulator’s name on the Debug button.

Click the Debug option to build and deploy your application to the Android emulator.

Debugging and Testing .NET Core Applications

Debug and Release are inbuilt in .Net configurations. Developers can debug with the debug build configuration and use the Release configuration to facilitate final release distribution. How does the Debug configuration work?

A program collates with full symbolic debug data without optimization. The relationship between generated instructions and source code can be complex, explaining why optimization will hinder debugging.

A program’s release configuration lacks significant debug data and is entirely optimized. Visual Studio Code launch settings leverages the Debug build configuration by default. This means developers won’t change it before debugging. Start the process by:

Launching Visual Studio Code

Opening the folder where you stored your .NET console application with Visual Studio Code.

Set a Breakpoint

A breakpoint interrupts the completion of an application temporarily before the line with the breakpoint can run.

Launch the Program.cs file

Click on the left margin of the code window to set the breakpoint along the line that shows the time, date, and name.

You can also set a breakpoint by either selecting Run > Toggle breakpoint from the menu when the line of code is checked or pressing F9.

Visual Studio Code will display a red dot along the left margin to highlight the line where the breakpoint is configured.

Launch the Program.cs file

Configure for Terminal Input

The breakpoint lies right after a Console.ReadLine method call. It’s important to understand that the Debug Console won’t authorize terminal input for running a program. To manage terminal input during debugging, a developer can leverage an external terminal or the integrated terminal. The example below uses the integrated terminal.

The Debugging Process

Launch the Debug view by checking the Debugging icon located on the left side menu. Choose the green arrow located right above the pane and adjacent to .NET Core Launch (console). Developers can also press F5 to launch the program in debugging mode, or select Run > Start Debugging from the menu.

Choose the Terminal tab to reveal the “What is your name?” command. The program displays this command while waiting for a response.

To respond to the command you’ll need to enter a string at the Terminal window, before pressing “Enter”

Program execution will stop once it gets to the breakpoint and right before the Console.WriteLine technique runs.

Using Unit Testing Frameworks for .NET Core Applications

Developers can complete unit testing using three core frameworks, all of which:

Feature test runner packages to facilitate the direct running of tests from Visual Studio

Slightly differ in feature and syntax set

Have console-oriented runners capable of running tests as a section of a CI/CD

Let’s discuss these frameworks in detail.

xUnit.NET

Besides being new, this framework is quite popular among developers and the .NET Core team. When running xUnit tests, the category with the test methods is epitomized separately for each test. This enables tests to run side by side while preventing data sharing. xUnit.NET is the default option for .NET Core web applications.

NUnit

The NUnit project is the inaugural open-source and robust unit test framework for the .NET world. Today, many developers still choose it for their unit testing needs. NUnit is also ideal for embedding a runner UI and unit tests into a Windows application.

MSTest

This is a testing framework for Microsoft. Previously, MSTest was easy to run from Visual Studio, yet it was also a bad choice. Automating the tests from CI/CD build servers was difficult. However, these problems are now a thing of the past with .NET Core. However, some C# developers opine that the changes came a little to late and has been overtaken by other frameworks.

Integrate Testing with .NET Core Applications

To integrate testing using .NET Core applications, a developer will need:

A test project to accommodate and complete the tests. The test project is recommended for the System under test (SUT)

Developers use the test runner to complete tests and generate answers.

The test project generates a test web host for the “system under arrest,” while using a test server client to manage requests and responses with the SUT.

Integration tests occur in the Arrange, Act, and Assert test steps sequence:

Configuration of the SUT’s web host

Creation of a test server client to present requests to the application

Execution of the Arrange step. The application prepares a request

Execution of the Act step, where the client generates the requests and gets a response

Execution of the Assert step, which involves validation of the actual response as a fail or pass, depending on an anticipated response

Continuation of the process to facilitate the execution of all tests

Reporting of the test results

Usually, the test web host configuration differs from the application’s web host for test runs. For instance, different application settings or different database can be used for the tests. The Microsoft.AspNetCore.Mvc.Testing package either provides or manages infrastructure elements like the in-memory test server and test web host. The Microsoft.AspNetCore.Mvc.Testing package manages various tasks, as seen below.

Configuration of the content root to the SUT’s project root. This enables static views/pages and files during test execution.

Copying of the dependencies file from the SUT into the test project’s directory

Offers the WebApplicationFactory category to simplify bootstrapping of the SUT with TestServer.

The unit tests report defines configuring a test runner and test project. It also features detailed instructions on how to run recommendations and tests for naming test classes and tests. Developers should always separate unit tests from integration tests into various projects. Doing so has the following benefits:

  • Facilitates control over the set of tests that are run
  • Prevents infrastructure testing components from being incorporated into the unit tests accidentally

Deploying .NET Core Applications

Developers can deploy a .NET core application as a self-contained deployment that features .NET Core binaries and the application or as a framework-dependent deployment that has the application binaries but relies on the .NET Core’s presence at the target system.

Framework-dependent Deployment

This process involves developing, testing, and publishing the application. Developers can follow these steps:

  • Build the project
  • Incorporate the app’s source code
  • Develop a Debug build for the application
  • Deploy the app

The resulting files are stored in the “publish” directory on Unix and the “Publish” directory on Windows systems.

The publishing process generates a program database with debugging data regarding your application. The file is essential for debugging exceptions. Developers may opt to eliminate it from their application’s files. However, saving it will be useful when you need to debug and release the application build. Deploy all the application files based on your preferences. For instance, you can package them with your preferred installation package use the copy command or wrap them in a Zip file. After installation, users can leverage the dotnet command to execute the application and define the application filename.

Self-contained Deployment Without Third-party Dependencies

This process involves building the project, redesigning the csproj file, creating, testing, and publishing the application. Here, developers will only follow two steps:

  • Project creation
  • Incorporate the application’s source code

Find out whether you will need globalization invariant mode. Suppose your application is built for Linux, globalization invariant mode will help you reduce deployment size. It is ideal for non-globally aware applications that can use casing conventions, formatting conventions, string comparison, and manage the invariant culture order. Right-click on the project in “Solution Explorer” to enable invariant more. Choose “Edit SCD.vbproj or SCD.csproj” and add the following to the file:

Develop a debug build of the application by:

Choosing Build > Build solution. Developers may also gather and run the debug build of the app by choosing Debug > Start Debugging. This step allows them to identify possible problems with the application as it runs on the host platform.

Testing it on every target platform is critical. Always test the app to determine whether the lack of culture-sensitive information is appropriate for the application if you have activated globalization invariant mode. Once the debugging process is done, publish the self-contained deployment.

Publishing a .NET Core Application

Publishing an application is the concept of producing a compiled app that a server can host. .NET Core SDK manages the publishing step. To publish an app:

Navigate to the Solution Explorer, right-click on the project, and choose “publish”

Access the pick a publish target option. Choose the “folder publish option”

Set the file share or folder path

Select the publish option

Deploying a .NET Core application to Azure

Build a new project in Visual Studio. Choose the ASP.NET Core Web Application as your template.

Set up the project, adding a valid name and location, then click “Create”

Select Web Application as seen below, > “Create”

asp.net core web application

Your sample .NET Core application is now ready.

Run the application to determine its appearance so you can validate it after it’s deployed to Azure.

Access the project in the Solution Explorer and click Publish. Visual Studio will generate various code publication options.

If you’re publishing into App Service, choose App Service > Create New option > Publish.

You will be directed to a screed where you can develop your inaugural Azure App Service.

Create a new hosting plan and resource group.

At this point, your screen will appear, as shown in the image below. Click “Create” to publish the .NET Core web app to Azure. Once published, the app will launch in the default browser.

NET Core web app to Azure

The publishing activity will be visible in the Window shown below. As you can see, the publishing is successful.

publishing activity

Deploying a .NET Core Application to AWS

Before starting the deployment process, ensure that:

You have an AWS account. If you can get one affiliated with an IAM user account, the better

The AWS Toolkit for Azure DevOps is installed on an on-premises Azure DevOps server or in Azure DevOps

An AWS elastic Beanstalk app and environment

A code project for a .NET framework which you’ll publish to the AZure DevOps project

Now, build a new AZure DevOps project, then upload your .NET framework files into it. Incorporate a new pipeline to the project based on the .NET framework template, which shall generate a web deploy archive to facilitate deployment.

To incorporate the AWS elastic Beanstalk deploy application task to build definition:

  • Choose the “+” button at the top of the task list. You can opt to work with the panel on the right side of your screen.
  • Type something inside the search box and scroll through until you find the AWS Elastic Beanstalk Deploy Application task.
  • Choose “ADD” to incorporate to the bottom of build definition.

Click “new task” to reveal its properties

Click the new task to see its properties in the right pane.

Configuring the Task Properties

If you’ve set up your AWS credentials for the project, choose them from the drop-down list. If you haven’t, select “New” to add credentials for the task.

Configure the AWS region where the Elastic Beanstalk environment is running

Define the name you used when creating the elastic Beanstalk app

Choose the environment name affiliated with the app name

Set the deployment bundle type field to the default

The web deploy archive is the complete path of the web deploy archive. Find this field’s value in the Build Solution task. The DesktopBuildPackageLocation argument is located in the MSBuild Arguments field. Remember, you can use the directory section of the full path in other tasks. For example, suppose the project was configured based on the above instructions. The value for the field would be “$build.artifactstagingdirectory\WebApp.zip.”

Once your new task is set up, you can run the build. Select “Save & queue” as seen below.

new task is set up

A log similar to the image below will appear after the build completes the running process.

build completes the running process

Building APIs with .NET Core

ASP.NET Core supports the creation of web APIs using minimal APIs or controllers. In a web APIS, controllers are categories that emanate from ControllerBase. You’ll need basic knowledge of object-oriented programming concepts to develop API with .NET Core.

What is an API?

APIs facilitate the communication of two software components through a collection of protocols and definitions. API stands for Application Programming Interface. Application is any software with a specific function, while Interface is a contract of service between two applications. The contract determines how the applications communicate using responses and requests.

Why use .NET Core for Building APIs?

.NET Core is a versatile app development framework with cross-platform support. Developers can use the framework for different chipsets and operating systems. .NET Core is open source and platform agnostic, facilitating cross-platform and interoperability development while offering significant scalability.

Since it’s open source, .NET Core can evolve fast, enabling the identification of more applicable functions. It can also be modified to support more operating systems to enhance cross-platform support. Further, security flaws can be identified and patched. .NET Core grants developers the freedom to use different architectures, hardware, and servers.

Creating a New API Project in .NET Core

Use this method to develop a controller-based API that uses a database. Here, you’ll need the Visual Studio 2022 with web development workload and ASP.NET.

Navigate to the “File Menu” and click New > Project

Enter “Web API” in the search box

Choose the ASP.NET Core Web API template and click Next

From the “Configure your new project” name your project TodoApi and click next to reveal the “Additional information dialog.”

Confirm you’re using the .NET 7.0 framework

Check the box for “Use controllers” and uncheck “to use minimal APIs.”

Click “Create”

Adding Controllers and Actions to the API

The Web API controllers developers add under this section must support CRUD(Create, Read, Update, and Delete) operations. The controllers communicate with the database layer via the Entity framework. Start by deleting the Controllers/ValuesController.cs. File. It contains a sample Web API that’s unnecessary in this case.

Next, create the project. The Web API scaffolding relies on reflection to identify the model classes. As a result, it’ll need the compiled assembly.

Navigate to Solution Explorer > right-click the Controllers folder > click Add > select Controller.

At the “Add Scaffold dialog” choose “Web API 2 Controller with actions, using Entity Framework”> Click Add.

Access the “Add Controller dialog”:

Navigate to the Model class dropdown option and choose the Author class. If it’s there, confirm whether the project is built.

Select “Use async controller actions.”

Don’t change the controller name. “AuthorsController.”

Click the “+” option next to Data Context Class.

Click Add to complete the “Add Controller dialog.” This will incorporate two classes to the project:

AuthorsController, which describes a Web API controller. The controller discharged the REST API that clients use to execute CRUD operations on the author’s list.

BookServiceContext, which oversees entity objects at run time, including continuing data to the database, change tracking, and populating objects with information from a database.

Here, create the project again and follow the same steps above to incorporate an API controller for Book entities. Choose Book for model class, and BookServiceContext class for the data context class. Don’t build a new data context.

Click “Add” to add the controller.

Implementing CRUD Functionality with Entity Framework Core

Get the appropriate software in your system, as seen below.

  • .NET 5.0 Preview SDK 2.0
  • Visual Studio 2019 16.6.0 Preview 2.
  • SQL Server 2017

To build an ASP.NET Core web application, follow the steps we’ve previously discussed in this article.

Install the appropriate NuGet packages compatible with the SQL Server database by:

Clicking the “Tools à NuGet Package Manager à Package Manager Console.”

Run the “Install-Package Microsoft.EntityFrameworkCore.Tools -Version 5.0.0-preview.2.20159.4” command in the Package Manager Console. The package facilitates the creation of the model class and database context from the database. The database provider ensures the Entiry Framework Cork is compatible with SQL Server.

Develop a database and link it with the application. Ensure you have the SQL Server 2017 in your system and:

Create a new inventory (database)

Suppose this application is about a table named Products with basic features. Paste the SQL query below on the query window, then run to create the table.

Create a new inventory

Run the “Scaffold-DbContext “Server=******;Database=Inventory;Integrated Security=True” Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models” scaffold prompt in the Package Manager Console. This will reverse design the database and develop the entity POCO classes and database context from tables. The scaffold command only creates POCO classes from tables with a primary key. The inventory context class and Products class will appear as shown below.

inventory context class and Products class

The auto-generated inventory Context class file features hard-coded database credentials in the “OnConfiguring method.”

Remove the parameterless constructor and OnConfiguring method from the context file.

Incorporate the connection string in the “appsetting.json file.”

Register the database context service on the application startup.

Incorporate the code below in the “ConfigureServices method” of your Startup file.

ConfigureServices method

Execute CRUD Operations

To modify controller actions to execute CRUD operations on IventoryContext:

Incorporate Controller Action

Integrate the products controller’s constructor in the “InventoryContext”

Use the code below in place of the controller.  

Incorporate Controller Action

Incorporate Controller Action

Incorporate Controller Action

Incorporate Controller Action

Incorporate Controller Action

Incorporate Controller Action

The code explains the actions and their purposes, as seen below:

Details: generate the product details from the products table via product ID. Suppose the product is unfound; generate a “NOT FOUND” result

Index: Generate all products from inventory and returns for viewing.

Create: Obtains product details as inputs and generates a new product in the inventory

Edit: Obtains the product details and ID as input. Suppose the product is unfound. It updates the details in the inventory.

Delete: Acquires the product ID as input, asks for confirmation, and deletes the product from inventory.

Server-side Validation

Add ModelState.IsValid check in the edit and add action. This will ensure users entered are valid based on the data validation concept included in the product’s metadata category. The Bind attribute is used in the edit and add action parameter. This facilitates binding of necessary properties from the user interface. To add view:

Create a new “Products under Views” folder

Click the “Products folder and click Add.” Choose “View and click the Razor View Empty template” Add these files:

  • cshtml
  • cshtml
  • cshtml
  • cshtml
  • cshtml

Use the code shown in the images below in place of what appears in the views.

Create

Create

Create

Delete

Delete

Delete

Details

Details

Details

Edit

Edit

Edit

Index

Index

Index

Client-side Validation

The client-side validation functions based on the rules added to the products’ metadata category with data annotation. It also shows validation messages. Worth mentioning is that this application features both client-side and server-side validation.

Run the Application

Click “Run” to view the app. A new browser tab will launch. Here, you’ll see the product listing page. However, the inventory will be empty.

Run the Application

Click “Create New” to incorporate new products to your inventory. That action will prompt the following screen.

Create New

Click Create but don’t fill in any data. The results will be as seen in the image below.

Click Create

Input data in the sections: product name, category, unit price, color, and quantity available.

Click Create.

The page will be something like:

Invebtorymanagement

Click details to reveal product details.

To update product details, click “Edit.” Modify product details accordingly, then click save.

To delete a product click “Delete.” You’ll get a confirmation prompt before the product is permanently deleted from the website.

Testing the API with Postman

Developers can use Postman to facilitate API testing. Here are simple steps to go about it.

Navigate to your Postman workspace

Click the “+” symbol to launch a new tab

Input the API Endpoint in the “Enter request URL” section and choose the action type GET for the request

Click the send button

Deploying the API to Azure

Deploying API to the Azure Arc-enabled Kubernetes group broadens API management support for multiple and hybrid cloud environments. Here is how to execute the process.

Navigate to the Azure Arc-connected clusture on the Azure portal

Choose “Extensions” from the left menu > + Add > API management gateway

Choose Create

Configure the gateways extension at the “Install API Management” gateway window.

Choose the resource and subscription group for the API management instance

Choose the Gateway name and API management instance from the Gateway details. Input a Namespace scope for the extension and various replicas if the API management service tier allows it

Select the default or a different configuration for your group in Kubernetes set up

Activate monitoring to upload metrics tracking requests to backend and gateway in the Monitoring tab. If its already activated, choose an existing Log Analytics workspace.

Click Review and install > install

Conclusion

Developers can test the deployed ASP.NET Core web API in Azure from the Azure portal by launching the Test tab > Get operation > select Send.

Secure Coding with .NET Core

ASP.NET Core features various libraries and tools developers can use to secure apps like third-party identity platforms like LinkedIn, Facebook, and Twitter. It also offers inbuilt identity providers.

Overview of Common Security Vulnerabilities

While there are numerous vulnerabilities targeting web applications, common examples that developers should beware of include:

  • Cross-Site Scripting (XSS) attacks
  • Cross-Site Request Forgery (XSRF/CSRF) attacks
  • SQL injection attacks
  • Open redirect attacks

How to Implement Secure Coding Practices in .NET Core

Often, application code can leverage the infrastructure from .NET Core. However, sometimes its important to incorporate additional application-based security. This can either be built by utilizing new ad hoc techniques to stretch the security system. Developers can use . NET-implemented permissions to create barriers to counter malicious code from accessing critical information. Further, it’s crucial to establish a balance between usability and security in all scenarios with reliable code.

When designing and writing code, developers should secure and limit the code’s access to resources. Here are techniques developers can use to secure their code.

  • Never use Code Access Security (CAS)
  • Avoid Distributed Component Object Model (DCOM)
  • Avoid the AllowPartiallyTrustedCaller attribute (APTCA)
  • Avoid partially trusted code
  • Avoid .NET Remoting
  • Avoid binary formatters

Preventing SQL Injection Attacks

To prevent SQL injection attacks in web applications, developers can leverage typed parameters, parameterized database queries with bound, and practice using parameterized stored processes in the database. Various programming languages can be used to accomplish this procedure, like .NET, Java, and PHP. Other SQL injection attack prevention measures include:

  • Ensuring web application software components like plug-ins, libraries, database server
  • software, web server software, and frameworks are updated with the latest security patches.
  • Avoid using shared database accounts between different applications or websites.
  • Leveraging the principle of least privilege.

Configure suitable error management and handling in the code and the web server. This will ensure database error prompts are not sent to the client’s web browser.

Protecting Against Cross-site Scripting (XSS) Attacks

Secure your app from XSS attacks with these steps.

Validate User Input

Don’t trust any data emanating from untrusted sources. Instead, validate all input data and adopt the known, acceptable, good input allowlist.

Escape User Input

Escaping is the ideal of converting the core characters in the data a web page receives to prevent it from being interpreted maliciously. It bars rendering of the special characters.

Clean Data

Analyze and remove unwanted data like HTML tags which experts say are unsafe. Maintain the safe data and eliminate all unsafe features.

Securing User Authentication and Authorization

To secure authentication and authorization, developers must externalize their identity stores and access controls where possible. This included adopting mediation techniques like API gateways. Gateways facilitate authorization and authentication by combining security logic in one location.

Developers, system administrators, and companies can also lock their APIs with Identity and Access Management (IAM) solutions and core management technologies. Still, it’s worth mentioning that authorization and authentication are insufficient for API security. Companies require tooling that can sense when malicious components can manipulate API calls and modify authorization or authentication parameters.

Implementing HTTPS for Secure Communication

HTTPS prompts a browser to encrypt the data it exchanges with a web page. Encryption hides data, reducing the chances of data viewing and manipulation. This is critical, especially for websites containing sensitive data such as financial information or personl details.

To incorporate HTTPS in your domain, you should install a TLS or SSL certificate on your website. Consult your web hosting provider for a reliable HTTPS security solution. You can also request a TLS or SSL certificate and install it independently. Remember, these certificates need to be renewed periodically.

Database Access with .NET Core

Data access is a critical part of every software application. .NET core supports a range of data access options like Entity Framework Core. It’s compatible with any .NET data access framework. The data access framework a developer uses depends on their application’s needs. Separating these options from the user interface projects and ApplicationCore and containing implementation details in infrastructure facilitates the development of testable and loosely coupled software.

Overview of Database Access in .NET Core

This guide will help you understand how to gain access to MySQL database in .NET Core with C#.

Step 1: Install MySQLConnector

Navigate to the command prompt and run dotnet add package MySqlConnector. You can also right-click your project and select “Manage NuGet Packages.” enter MySqlConnector in the search box and complete the installation.

Step 2: Connection String

A model MySQL string would be:

Connection String

Replace the values in the string with the suitable settings for your database. When using .NET Core, the connection string will be stored in

connection string

Step 3: Set up the ASP.NET Core

Register a database connection in:

Set up the ASP.NET Core

Step 4: Launch and Use Connection

The MySqlConnection object in .NET Core will be dependency-injected into your Controller group. Launch the connection and perform a query as shown below.

Launch and Use Connection

Connecting to a Database Using .NET Core

Launch Visual Studio and click File > New > Project. Select the “Console Application (.NET Core)” button and click OK.

Install a dependency the (“Microsoft.EntityFrameworkCore.SqlServer”) package with NuGet Package Manager. There are two key methods of linking to the SQL Server in .NET Core.

  • Via scaffolding command
  • Via JSON configuration file

In this guide, let’s use the scaffolding method.

Before the scaffold, introduce a new “Models” folder to the Solution. You can choose a different name.

Launch the NuGet console from Tools > Nuget Package Manager > Package Manager Console. Paste the command below, but you’ll need to change it to fit your needs.

Package Manager Console

Click enter. The above command will generate the following categories:

Server -> the IP address and name of the database host

User Id -> your SQL Server login id.

DataBase -> name of your database

Password -> the SQL Server password for the specific user Id.

OutputDir -> a folder in Visual Studio where you store your Models classes

Suppose you’re logging in via the Windows Authentication method. Replace the “User ID” and “Password” parameters with “Trusted_Connection=True”

Performing CRUD Operations with .NET Core

To Execute CRUD operations in .NET core, follow these steps.

  • Build a respository
  • Create a .NET Core application
  • Link the application with the repository
  • Build all the CRUD operations in your application
  • Test the app
  • Host your application in Kestrel or IIS

Refer to our previous comprehensive guide on implementing CRUD functionality with entity.

When Should I Use .NET Core?

When Should I Use .NET Core

You can use .NET Core to build anything and for every platform or computing architecture out there.  The development platform has all the tools, libraries, dependencies, and documentation you need. From mobile applications to web applications (using razor pages), desktop applications to microservices to containers, cloud applications, IoT apps, machine learning solutions, games, etc.

However, as a development platform, .NET core excels or is heavily used in the following areas:

Building Cross-Platform applications

use .NET Core if you need to develop solutions that can run on multiple platforms and you have developers using all three major OS platforms. This is often the case in large organizations or startups building complex enterprise-level solutions across multiple teams.

If you use C#, Visual Studio, Azure, and other Microsoft products

You will find it easier and more convenient to develop inside .NET Core if you primarily develop in a Microsoft environment using their tools and services such as Azure. Most developers who use C# work in .NET Core even though they may use other languages like JSON, CSS, and Typescript to add functionality to their applications.

If you develop With Microservices and Containers

.NET Core is the best dev platform for developing within the Microservices architecture where applications are arranged into independent services. Also, use .NET core if your project needs the use of Docker containers because it excels in the app container deployment approach.

Building Large, Scalable Enterprise applications

.NET Core is by far the most preferred platform for building large enterprise-level solutions that run natively or in the cloud. Microsoft has dedicated most of its resources to providing secure, scalable, and efficient business solutions for businesses.

You Need Horizontal and Backwards Compatibility

Use .NET Core if you need compatibility with solutions developed in .NET, Visual Basic, and other older systems or if working with multiple .NET frameworks concurrently.

What Is .NET Core Cross-Platform?

Cross-platform support means that .NET Core is compatible across computer platforms. You can develop and run .NET core applications in a Windows environment, Mac Os as well as Linux. All major computing architectures are also supported natively. You will not need to install third-party porting tools to implement solutions developed in a different platform other than the one you are currently using.

What are the benefits of .NET Core?

Since it was introduced, .NET Core has made a name for itself as being a versatile, scalable, secure, and easy-to-use software development environment. It has solid corporate backing in addition to the large open source community .NET Core also provides developers with an easy and cost-effective way to build and develop solutions across platforms and architectures.

You will have access to Microsoft’s robust development tools such as Visual Studio and Visual Studio Code as well as third-party dev tools, libraries, and dependencies.NET Core is also liked because it’s fast, modern, user-friendly, and lightweight due to the use of independent Nuget packages.

What Is the Latest Version Of .NET Core?

What Is the Latest Version Of .NET Core

The last version of .NET Core was 3.1 last updated in August 2022. However, Microsoft adopted a more unified and traditional naming system with new versions of the same platform dropping the word “Core”. The current stable version of .NET Core with long-term support (LTS) is NET 6.

Conclusion

.NET Core is a unified, solid, and agile framework for building web APIs and web UI. It’s compatible with multiple operating systems, is community-based, and is open-source. Apart from being high-performance and lightweight, this framework has inbuilt dependency injection. Its unique features make it popular among developers.

Microsoft launched .NET Core 7.0 late last year (2022). The company introduced the first preview of .NET Core 8 recently. The future of .NET Core is bright. Visit our website for more software development related content.

Resources for Learning More About .NET Core

Visit these links for more details on .NET Core.

  • https://learn.microsoft.com/en-us/aspnet/overview
  • https://learn.microsoft.com/en-us/aspnet/core/introduction-to-aspnet-core?view=aspnetcore-7.0
  • https://learn.microsoft.com/en-us/aspnet/core/host-and-deploy/azure-apps/?view=aspnetcore-7.0
  • https://learn.microsoft.com/en-us/aspnet/core/getting-started/?source=recommendations&view=aspnetcore-7.0
  • https://learn.microsoft.com/en-us/aspnet/core/introduction-to-aspnet-core?source=recommendations&view=aspnetcore-7.0
  • https://learn.microsoft.com/en-us/aspnet/core/mvc/overview?source=recommendations&view=aspnetcore-7.0
  • https://learn.microsoft.com/en-us/aspnet/core/tutorials/first-mvc-app/start-mvc?source=recommendations&view=aspnetcore-7.0&tabs=visual-studio

Apart from web publications, you can learn about .NET Core from:

  • Books
  • Courses
  • Tutorial sites
  • YouTube Channels
  • Courses
  • Blogs