Getting Started With Web Application Using ASP.NET Core 2.2 With Visual Studio 2017

Getting Started With Web Application Using ASP.NET Core 2.2 With Visual Studio 2017


To follow this guide it is required to have the following:

  1. Basic knowledge of C# programming and understanding of  HTML, CSS & JavaScript Web technologies. 
  2. Visual Studio 2017 (Community or any commercial edition) is installed on the development computer. SQL Express is also required and comes with the Visual Studio installer. Remember to install it as well.
  3. Follow the Step By Step Guide For Creating  ASP.NET Core 2.2 C# Web Application Using Visual Studio 2017

The completed web application project using the above tutorial builds a website as shown below. 


Figure 1: Final Website


Here I am going to discuss some useful information about the application we created.  

Step1. Examining The Project

The project we created using ASP.NET Razor Web Page Application is added to the solution, as shown in the Solution explorer, where it displays the folder structure. It has 3 main files, 6 folders one project item(Connected Service).



Figure 2: Default files and folders created by the template.

Any project created using any ASP.NET Core Web application templates consists of Program.cs, Startup.cs & appsettings.json files and Dependencies & Properties folders and a project item Connected ServicesSince we used ASP.NET Core Razor Pages Web Application, there are a few more folders with files inside added to the project by the template wizard. Those are wwwrootAreas, Data, and Pages folders. 
Wizard adds a few more files inside all of those folders except the Connected Services folder. We will examine them when required.

Program.cs

The Program.cs file is the starting point of any ASP.NET Core Web Application created using the template wizard. 

using  Microsoft.AspNetCore;
using  Microsoft.AspNetCore.Hosting;


namespace  RazorWebApp1
{
    public class  Program 
    {
        public static void  Main(string[]  args)
        {
            CreateWebHostBuilder(args).Build().Run();
        }

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

This Program class has two methods:
  • public static void Main(string[] args)
  • public static IWebHostBuilder CreateWebHostBuilder(string[] args)

The Main method is the first method to execute when the application is run. It calls another static method (rather an expression-bodied methodCreatWebHostBuilder(args) of type IWebHostBuilder which will create and configure a host builder object.  And then calls Build and Run methods on that object to build the host and run the web application.

In other words, the host is configured and launched before the app is configured and started.

A host is an object that encapsulates all of the app's resources, such as:

  • Dependency injection (DI) 
  • Logging 
  • Configuration 

Startup.cs



The Startup class configures services and the Application's request pipeline.

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.UI;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using RazorWebApp1.Data;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace RazorWebApp1
{
    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.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlServer(
                    Configuration.GetConnectionString("DefaultConnection")));
            services.AddDefaultIdentity<IdentityUser>()
                .AddDefaultUI(UIFramework.Bootstrap4)
                .AddEntityFrameworkStores<ApplicationDbContext>();


            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
		}	
			

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
            }
            else
            {
                app.UseExceptionHandler("/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.UseCookiePolicy();

            app.UseAuthentication();
            
	    app.UseMvc();
        }
    }
}


 The Startup class includes the following:

  • ConfigureService - method to configure the application's services. A service is a reusable component that provides app functionality. Services are registered in ConfigureServices and consumed across the app via dependency injection (DI)
  • Configure - method to create the app's request processing pipeline.

appsettings.json


appsetting.json file is the default settings file or some refer to it as a configuration file or application configuration settings file,  added when creating the Web Application project using the Template wizard. 

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=aspnet-RazorWebApp1-53bc9b9d-9d6a-45d4-8429-2a2761773502;Trusted_Connection=True;MultipleActiveResultSets=true"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*"
}

This file is loaded during host building by calling CreateDefaultBuilder in the CreateHostBuilder method. As we can see in the above code it has the connection string and Logging settings in JSON format. The default setting added in this file by the wizard depends on the template we select. Since we selected user accounts it added these connection string settings, if we use an empty project it will only add Logging settings, etc.

Folders added by the Template


Apart from the above 3 files, there are a few more files inside a few top-level folders. The added top-level folders by the Razor web page Web Application template are:

  • Connected Services
  • Dependencies 
  • Properties 
  • wwwroot 
  • Areas 
  • Data
  • Pages

The following figure shows the Windows Explorer folder structure of the project.


Figure 3: Project files in Windows Explorer

Now we take a look at the folder structure in the Solution Explorer window (Figure 2  above and Figure 4 below.


Figure 4: Expanded Solution folders

First, four top-level folders have special icons while other folders look similar to Windows Explorer folders. Except for Connected Services and  Dependencies folders, all other folders are physical folders even though some of them have special icons in the Solution Explorer.

Connected Services

This folder keeps service references to other services that the applications need to communicate with. If you right-click and select...Add Connected Services it will show the available service categories for the project


Figure 5: Connected Services

Dependencies

This folder keeps all assemblies related to the project. Inside Dependencies, there are a few more subfolders namely Analyzers, Frameworks and Packages. For example, we can add service references or NuGet packages to the project and they will appear inside these folders depending on the selection. The packages folder shown in the above Solution Explorer figure shows the packages added to the project by the template.

The following packages are added to the project when Individual User Accounts options are selected during the project creation wizard:
  • Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore
  • Microsoft.AspNetCore.Identity.EntityFrameworkCore
  • Microsoft.AspNetCore.Identity.UI
  • Microsoft.EntityFrameworkCore.SqlServer
  • Microsoft.EntityFrameworkCore.Tools

Properties

The template adds the launchSettings.json file to the project. This file contains the project set to launch the application.

{
  "iisSettings": {
    "windowsAuthentication": false, 
    "anonymousAuthentication": true, 
    "iisExpress": {
      "applicationUrl": "http://localhost:3438",
      "sslPort": 44391
    }
  },
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "FirstWebPageApp": {
      "commandName": "Project",
      "launchBrowser": true,
      "applicationUrl": "https://localhost:5001;http://localhost:5000",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}

To modify these settings we can manually edit this file, but the best way to edit the file is to use debug tab of the project properties graphical tab. We can access it by right-clicking on the project name in the Solution Explorer and selecting Properties from the context menu and then selecting the debug tab on the left to edit these project launching settings.


Figure 6: Debug options in Project Properties


Any changes to the fields in the tab will be saved to the launchSetting.json file when the project is saved.

wwwroot

This folder contains all the files related to the UI. The following expanded wwwroot folder shows the available files.



Figure 7: Expanded wwwroot folder

This is where we keep all static files for the web user interface(UI). The template uses Bootstrap v4.3.1 and jQuery JavaScript Library v3.3.1 in Visual Studio 2017. These files can be updated or add new libraries using the "client-side Library" tool. In addition to these files, all web site related images or image folders should be stored inside the wwwroot folder.

👍   As a rule of thumb, for the convenience of other developers:
  • Any new stylesheet that is required for customising the project should go under the css folder.
  • Any new javascript file required for customising the project should go under the js folder.
  • DO NOT put any custom file related to the project under the lib folder.

Figure 8: Top-level wwwroot folder items.

The website icon named favicon.ico is also located under the wwwroot folder. We can change the website icon by replacing this file with our own logo. Remember the file should be named exactly as favicon.ico.

Areas

When using the ASP.NET Core Web application template, this folder and related files are added inside this folder only when the Individual User Accounts option is selected during the project setup wizard. This adds the identity framework related _ViewStart.cshtml together with folder structure. If we use Identity Framework scaffolding to override defaults more folders and files will be added to the Identity subfolder in this Area folder.

Data

As the name implies this folder holds all the data-related files. This folder is also added when the Individual User Accounts option is selected during the project setup wizard. ASP.NET Core Identity Framework uses Microsoft Entity FrameworkCore. The following files are added:

  • ApplicationDbContext
  • Migrations/00000000000000_CreateIdentitySchema.cs
  • Migrations/ApplicationDbContextModelSnapshot.cs

Pages

ASP.NET Core use the Pages folder to store all the Views related razor syntax files and supporting files. Each Razor page consists of two files in the format fileName.cshtml and fileName.cshtml.cs. 
  • A .cshtml file contains HTML markup with C# code using Razor syntax.
  • A .cshtml.cs file contains C# code that handles page events or controller actions.

The Template added the following  razor files:
  • Index.cshtml & Index.cshtml.cs
  • Privacy.cshtml & Privacy.cshtml.cs
  • Error.cshtml & Error.cshtml.cs

and the following supporting files (not paired with a .cs file):
  • _ViewStart.cshtml
  • _ViewImports.cshtml
  • Shared/_CookieConsentPartial.cshtml
  • Shared/_Layout.cshtml
  • Shared/_LoginPartial.cshtml
  • Shared/_ValidationScriptsPartial.cshtml
We will take a look at some important files.

_Layout.cshtml

The  _Layout.cshtml file configures sitewide features common to all pages. This file sets up the sitewide scripts, stylesheets, navigation menu at the top of the page and the footer contents at the bottom of the page. The concept is similar to Master Pages in classic ASP.NETforms.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>@ViewData["Title"] - RazorWebApp1</title>
 
    <environment include="Development">
        <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.css" />
    </environment>
    <environment exclude="Development">
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
              asp-fallback-href="~/lib/bootstrap/dist/css/bootstrap.min.css"
              asp-fallback-test-class="sr-only" asp-fallback-test-property="position" asp-fallback-test-value="absolute"
              crossorigin="anonymous"
              integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T"/>
    </environment>
    <link rel="stylesheet" href="~/css/site.css" />
</head>
<body>
    <header>
        <nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3">
            <div class="container">
                <a class="navbar-brand" asp-area="" asp-page="/Index">RazorWebApp1</a>
                <button class="navbar-toggler" type="button" data-toggle="collapse" data-target=".navbar-collapse" aria-controls="navbarSupportedContent"
                        aria-expanded="false" aria-label="Toggle navigation">
                    <span class="navbar-toggler-icon"></span>
                </button>
                <div class="navbar-collapse collapse d-sm-inline-flex flex-sm-row-reverse">
                    <partial name="_LoginPartial" />
                    <ul class="navbar-nav flex-grow-1">
                        <li class="nav-item">
                            <a class="nav-link text-dark" asp-area="" asp-page="/Index">Home</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link text-dark" asp-area="" asp-page="/Privacy">Privacy</a>
                        </li>
                    </ul>
                </div>
            </div>
        </nav>
    </header>
    <div class="container">
        <partial name="_CookieConsentPartial" />
        <main role="main" class="pb-3">
            @RenderBody()
        </main>
    </div>
 
    <footer class="border-top footer text-muted">
        <div class="container">
            &copy; 2019 - RazorWebApp1 - <a asp-area="" asp-page="/Privacy">Privacy</a>
        </div>
    </footer>
 
    <environment include="Development">
        <script src="~/lib/jquery/dist/jquery.js"></script>
        <script src="~/lib/bootstrap/dist/js/bootstrap.bundle.js"></script>
    </environment>
    <environment exclude="Development">
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"
                asp-fallback-src="~/lib/jquery/dist/jquery.min.js"
                asp-fallback-test="window.jQuery"
                crossorigin="anonymous"
                integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=">
        </script>
        <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.bundle.min.js"
                asp-fallback-src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"
                asp-fallback-test="window.jQuery && window.jQuery.fn && window.jQuery.fn.modal"
                crossorigin="anonymous"
                integrity="sha384-xrRywqdh3PHs8keKZN+8zzc5TX0GRTLCcmivcbNJWm2rs5C8PRhcEn3czEjhAO9o">
        </script>
    </environment>
    <script src="~/js/site.js" asp-append-version="true"></script>
 
    @RenderSection("Scripts", required: false)
</body>
</html>
 

_ViewStart.cshtml


This file indicates the layout file used for the application.
@{
    Layout = "_Layout";
}
Code that needs to run before each view or page should be placed here. By convention, the _ViewStart.cshtml file is located in the Pages folder. The statements listed in _ViewStart.cshtml are run before every full-page view (not layouts, and not partial views). _ViewStart.cshtml  and _ViewImports.cshtml(we will look at this file in the next section), are hierarchical. If a _ViewStart.cshtml file is located one or more levels down in the folder hierarchy, it will be run after the one defined in the root of the Pages folder.

_ViewImports.cshtml

This is a common file to specify namespaces to import. Razor directives shared by many pages are declared here. 

@using Microsoft.AspNetCore.Identity
@using RazorWebApp1
@using RazorWebApp1.Data
@namespace RazorWebApp1.Pages
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
  • The _ViewImports.cshtml file doesn't support other Razor features, such as functions and section definitions. 
  • A _ViewImports.cshtml file can be placed within any folder, in which case it will only be applied to pages within that folder and its subfolders.
  • _ViewImports files are processed starting at the root level and then for each folder leading up to the location of the page or view itself. 
  • _ViewImports settings specified at the root level may be overridden at the folder level.

_ViewStart.cshtml and _ViewImports.cshtml are not typically placed in the /Pages/Shared folder. The app-level versions of these files should be placed directly in the /Pages folder.

Hope this helps you create an ASP.NET Core 2.2 Razor Pages Web Application.

Reference:

Comments

Popular posts from this blog

Examining the Project structure - ASP.NET Core 7 Part 4

Getting Familiar with Visual Studio 2022 IDE - ASP.NET Core 7 Part 3

Displaying A Start Page In ASP.NET Core 3.1 Web API Project.