ASP.NET Core Tutorial

ryanthelin

Ryan Thelin

Posted on March 22, 2021

ASP.NET Core Tutorial

ASP.NET is the web app building tool for Microsoft's .NET Core platform. It is used extensively for enterprise or cloud-enabled applications and is suitable for MVC full-stack or back-end development.

Following the growing popularity of cloud computing and scalable web apps, .NET has been steadily rising in demand. More companies are interested in the unique combination of cross-platform and scalable technology, resulting in more job opportunities for .NET developers.

Today, we'll help you get started with ASP.NET Core by exploring its MVC structure and help you through your first ASP.NET Core web application!

Here’s what we’ll cover today:

Learn full-stack .NET Core in half the time

Get hands-on practice with all the most tested concepts of .NET Core.

Developing Applications with ASP.NET Core

Alt Text

What is .NET Core?

.NET Core (often shortened to ".NET") is an open-source, C# software framework created by Microsoft in 2016. It is the successor to the .NET Framework and differentiates itself with cross-platform capabilities. While .NET Core does not yet have access to as many libraries as .NET Framework, it is still regularly updated and is projected to continue updates well into the future. These two technologies have recently been merged in November of 2020 into a new framework called .NET 5.

ASP.NET (Active Server Pages) extends .NET Core with tools to build server-side web applications. It uses the MVC architecture to generate its UI and web standard HTML, CSS, and JavaScript to generate behaviors. It includes extensive support for web APIs, cloud-based web applications, and scalability.

It's also built from the ground up to work with popular tools like Docker, Visual Studio, Kestrel, jQuery, and more. .NET is often used with Entity Framework Core, an object-relational mapping framework helpful for working with databases.

While often overlooked, ASP.NET is a strong stack to know because of its wide popularity in enterprise companies like banks, business-to-business sellers, and investment firms. Some notable users of ASP.NET are Slack, Mastercard, and Alibaba.

Features of .NET vs. ASP.NET

.NET Core includes:

  • Cross-platform support for different computer operating systems, mobile devices, and even game consoles.
  • Support for C#, F#, and Visual Basic programming languages
  • Base libraries for working with strings, dates, files/IO, etc.
  • Editors and tools for Windows, Linux, macOS, and Docker

ASP.NET adds:

  • Support for processing web requests in C# or F#
  • Razor page templating syntax for building dynamic web pages using C#
  • Libraries for common web patterns like MVC
  • An authentication system featuring libraries, a database, and template pages for handling logins with multi-factor authentication and external authentication with third-parties like Google, Twitter, Facebook, etc.
  • Editor extensions that implement syntax highlighting, code completion, and other functionality tuned for web development.

ASP.NET MVC Project Structure

Many developers choose to complete their ASP.NET Core projects in MVC structure because of its widespread popularity.

Let's walk through each of the core components found in an average MVC structured ASP.NET Core web app.

Alt Text

Models

/Models/ is the "M" in MVC. The /Models/ folder contains all of your model classes. By default, this folder only has the ErrorViewModel.cs file which is a default file that handles exceptions.

Model classes allow you to map data to your database. A model class usually consists of attributes along with their “getter” and “setters”. Attributes are essentially the data that any instance of this model class should have values for.

The number of model classes and types of attributes in those model classes depends on your application requirements. For example, an app that manages employee data could have a model class Employee with attributes name, department, and rank because these attributes apply to all employees.

public class User
{
    public int ID { get; set; } //ID attributes are recognized as keys for the object by Entity
    public string Name { get; set; }
    public string Email { get; set; }
    public string Password { get; set; }
    public string PhoneNumber { get; set; }
    public bool IsActive { get; set; }
}
Enter fullscreen mode Exit fullscreen mode

Controllers

/Controllers/ is the "C" in MVC. The /Controllers/ folder consists of all of your controller classes. By default, it has the HomeController.cs file in it.
Controller classes are where your application logic resides. .NET requires every controller class to implement the IController interface as it contains essential support for views.

public class UsersController : Controller
Enter fullscreen mode Exit fullscreen mode

Controllers are also where you implement dependency injection, which establishes a connection between controllers and your database context. This allows you to use _context throughout your controller class to access your database without having to initialize any object.

Methods inside a controller are called “action methods” as they return an "action result". The name of an action method is used to map its URL endpoint. For example, if the controller name is UserController and the name of an action method is Details, then there is a URL endpoint /Users/Details/ that can be accessed and that will trigger the Details action method.

This ability to access different pages under the same domain name is called Routing. Incoming HTTP requests are matched with the corresponding URL endpoint (often an action method), which then returns your programmed response. Similar to routes in computer filing systems, different parts of the route are differentiated by slashes: Domain/Model/method

The framework extracts the route from the name of the controller. For example, if a controller’s name is UsersController, your route will be /Users.
A URL of the form Controller1/Method1 maps to a method named Method1 in the Controller1 class. If the name of the Users class method is SignUp(), then the route will be /Users/SignUp/.
The default action method triggered when a user accesses the controller URL is Index(). This executes the behavior set in the Index.cshtml file in the views folder.

// GET: Users
public async Task<IActionResult> Index()
{
    return View(await _context.Users.ToListAsync());
}
Enter fullscreen mode Exit fullscreen mode

Views

/Views/ is the "V" in MVC. The /Views/ folder contains all of your files that will be used to display a UI to the user that they can interact with. By default, this folder has two more folders: /Home/ and /Shared/. Both Index.cshtml and _Layout.cshtml folders are mostly responsible for your output.

Views allow users to see your data in a user-friendly format. They are responsible for anything your end-user sees on their screen. Views in ASP.NET are written in Hypertext Markup Language (HTML and CSS), along with some additional syntax to represent dynamically changing data.

The views generated maps to your controller’s action methods. For example, the Index() method has a mapped view called Index.cshtml and Create() method has a view called Create.cshtml and so on.
Files in the Views folder that use methods or data from models must have a model declaration at the start that allows you to access the attributes of the listed model class.

@model IEnumerable<<t>People.Models.User</t>> 
Enter fullscreen mode Exit fullscreen mode

In this case, you can read and extract data and attributes from User classes.
The simplest view request is an attribute request. This allows you to read the value of an attribute from a paired model class.

@Html.DisplayNameFor(model => model.Name)
Enter fullscreen mode Exit fullscreen mode

Here is an example of an Index.cshtml file in Views that displays simple text. As it does not call any methods or use any model data, we do not need to link a model at the start.

@{
    ViewData["Title"] = "Home Page";
}
<div class="text-center">
    <h1 class="display-4">Welcome</h1>
    <p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>
</div>
Enter fullscreen mode Exit fullscreen mode

Properties

The /Properties/ folder contains a launchSettings.json file. This file tells the framework how to launch this application.

It conveys the information by describing which commands to run, the environment variables to set, and the applications (such as a browser) to launch with the application. .NET Core uses this information to not only run the application but for debugging purposes as well.

{
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:1779",
      "sslPort": 44366
    }
  },
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "People": {
      "commandName": "Project",
      "launchBrowser": true,
      "applicationUrl": "https://localhost:5001;http://localhost:5000",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

/Startup.cs and /Program.cs

This is where your application starts. .NET Core is a console application configured to run a web application.

Program.cs contains your main method and Startup.cs contains all your beginning configurations. These configurations are essentially instructions on how you want the application to start and execute.

// Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace People
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }
        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });
    }
}

Enter fullscreen mode Exit fullscreen mode
// Startup.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace People
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = 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.AddControllersWithViews();
        }
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseRouting();
            app.UseAuthorization();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

appsettings.json

appsettings.json is used to write connection strings or application-specific settings. You can use it to store different configuration settings that include database connection strings, setting up a variable with a global scope, and more.

appsettings.Development.json is similar, but it is only used in a development environment. So, any configurations applied here will not be reflected in the production environment.

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"
}
Enter fullscreen mode Exit fullscreen mode

.csprof

.csprof is an XML file. When a new project is created, you receive a file with the same name that you set the project’s name to, and its extension will be .csprof. This file represents a C# project file.

Here's an example:

<Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>netcoreapp3.1</TargetFramework>
  </PropertyGroup>
</Project>
Enter fullscreen mode Exit fullscreen mode

Non-MVC Architectures

Razor Pages

Razor Pages are the default web development format in ASP.NET Core. They're a page-based model built into ASP.NET Core MVC. It has similar features to MVC but has its own syntax and a less cluttered layout.

In MVC style, parts of your application are broken into folders for controller, model, and view. The Razor Pages structure doesn't have separate folders and instead uses a single "Pages" folder as a route folder for all parts.

Alt Text

Instead of a separate controller with actions and each action representing a view, Razor Pages are a compact version MVC style that attaches the controller or view model directly to the page.

Repository

Repositories are a special type of class used to add an abstraction layer between data access and your controllers. It is not used in MVC formatted programs but is important to other types of ASP.NET Core apps, such as Razor Pages apps.

This helps promote loose coupling, isolate your application from changes in the data store, and facilitates unit testing. It also saved you from writing the same queries across multiple controllers that achieve the same purpose.

First, you create an interface with all of the declarations of the functions responsible for performing CRUD operations. Then, you create a repository class and inject your database context. These repository classes implement the interface’s functions and provide their logic for handling operations. One of these repositories is then injected into your controller to provide functionality and so you don't need to inject your database directly into your controllers.

public interface IUserRepo
{
    User CreateUser(User user);
    IEnumerable<User> GetAllUsers();
    User GetUserById(int id);
    User UpdateUser(User user);
    User DeleteUser(int id);
}
Enter fullscreen mode Exit fullscreen mode

It's best practice to title all C# interfaces with the prefix "I" to indicate their interface status at a glance.

JSON Web APIs

JSON is an acronym for JavaScript Object Notation. It is a file format that stores data objects in a human-readable form. It is the most popular format when it comes to creating and consuming APIs. Many applications are developed with ASP.NET at the back-end and get implemented into a front-end framework like React, Blazor, Bootstrap, or Angular using JSON web APIs.
Here's an example of a JSON file:

[
    {
        "id":1,
        "name":"James Bond",
        "email":"James@Bond.co.uk",
        "password":"password",
        "phoneNumber":0070000000
    }
]
Enter fullscreen mode Exit fullscreen mode

The square brackets [ ] indicate a list or an array of objects. Curly brackets { } represent a JSON object. Inside this object, there are key-value pairs of different data types, key "name" with value "James Bond".

JSONs are manipulated with a set of HTTP methods similar to CRUD. Every HTTP request uses a specific method. The default method is GET, but you can use POST, PUT, or DELETE if you want different behaviors.

GET

The GET method is used to fetch a resource from the server to the client. In the case of JSON web APIs, the resource can be a JSON object or a list of JSON objects.

GET /index.html
Enter fullscreen mode Exit fullscreen mode

POST

The POST method is used to send data from the client to the server. The server then saves the data. In the case of JSON web APIs, this can be a JSON object or a list of JSON objects.

POST /test
Enter fullscreen mode Exit fullscreen mode

PUT/PATCH

Both PUT and PATCH are used to modify data. However, there is a slight difference between the two. In PUT, the entire object is replaced with a new object. Whereas in PATCH, only the modified part of an object is replaced.
This is similar to the Update method in CRUD.

PUT /new.html HTTP/1.1
PATCH /file.txt HTTP/1.1
Enter fullscreen mode Exit fullscreen mode

DELETE

The DELETE method is used to send a request from the client to the server or to delete a record. The server takes the request and removes the record accordingly.

DELETE /file.html HTTP/1.1
Enter fullscreen mode Exit fullscreen mode

Hello World: How to create an ASP.NET web app

Now, let's get hands-on and write your first Hello-World. For this example, we'll use Razor Pages and .Net Core CLI as these are the default tools. You'll also need .NET Core 3.1 SDK or later for everything to work properly.

Create a project

Open your command shell, and enter the following command:

dotnet new webapp -o aspnetcoreapp
Enter fullscreen mode Exit fullscreen mode

This will create a new web app, indicated by the webapp parameter.

The -o aspnetcoreapp parameter creates a directory named aspnetcoreapp with all the source files for our app.

Trust the development certificate

Now enter:

dotnet dev-certs https --trust
Enter fullscreen mode Exit fullscreen mode

This sets your computer to trust the HTTPS development certificate. Without this step, later commands will be blocked.

Run the app

Next, enter:

cd aspnetcoreapp
dotnet watch run
Enter fullscreen mode Exit fullscreen mode

This selects the web app project created in step 1, then tells .NET to run it.

Once the command shell tells you it has started, copy the following into your browser bar: https://localhost:5001.

Edit Razor Page

Open Pages/Index.cshtml and modify the <p> text to say:

    <p>Hello, world! The time on the server is @DateTime.Now</p>
Enter fullscreen mode Exit fullscreen mode

Afterward, your file should look like this:

@page
@model IndexModel
@{
    ViewData["Title"] = "Home page";
}
<div class="text-center">
    <h1 class="display-4">Welcome</h1>
    <p>Hello, world! The time on the server is @DateTime.Now</p>
</div>
Enter fullscreen mode Exit fullscreen mode

Once you're done, save the file and refresh your browser to the same localhost IP. You'll see a nice welcome message!

This step is the same using either the MVC or Razor Page approach.

Advanced concepts to learn next

Congratulations on completing your first .NET Core application! You're off to a great start in your bright .NET career.

Some next concepts to learn along your journey are:

  • .NET apps debug techniques
  • Database seeding
  • Authentication
  • Custom SQL Queries
  • Validation
  • Tag Helpers
  • Middleware

To help get you up to speed quickly, Educative has created the course Developing Applications with ASP.NET Core. This course will walk you through each of these advanced concepts with hands-on code practice.

By the end, you'll have the .NET skills you need to stand out in future interviews.

Happy learning!

Continue reading about software architectures

💖 💪 🙅 🚩
ryanthelin
Ryan Thelin

Posted on March 22, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

ASP.NET Core Tutorial
webdev ASP.NET Core Tutorial

March 22, 2021