Your First ASP.NET Core 1.0 App

Introduction

Recently, Microsoft released RC2 of ASP.NET Core 1.0. You can build ASP.NET Core 1.0 applications using Visual Studio 2015. There is a Web Application project template that creates a basic Web application for you. This template adds several pieces of a basic Web application. However, for the sake of learning, may want to skip this template and create an empty Web application. You then can add the required pieces yourself. To that end, this article illustrates how an ASP.NET Core 1.0 application can be built using the Empty project template.

Note: This article uses RC2 of ASP.NET Core 1.0. Make sure to install it on your machine before you follow the instructions discussed below. To know how to install RC2 of ASP.NET Core 1.0, you may want to read this article.

Creating a New Project

Let's begin by creating a new project in Visual Studio 2015. Select the File > New Project menu option to open the New Project dialog, as shown in Figure 1:

First1
Figure 1: Creating a new project

As you can see, there are three items in the dialog. The first item is for creating traditional ASP.NET Web applications using Web Forms and MVC. The second item is for creating ASP.NET Core 1.0 applications that target .NET Core 1.0. Finally, the third item is for creating ASP.NET Core 1.0 applications that target .NET Framework. For this example, select ASP.NET Core Web Application entry, give some project name, and click OK.

You then can select a project template, as shown in Figure 2:

First2
Figure 2: Selecting a project template

As you can see, there are three project templates, namely Empty, Web API, and Web Application. Select the Empty project template and click OK. This will create a new project using the empty template and your Solution Explorer will resemble Figure 3:

First3
Figure 3: Viewing the Solution Explorer

Add Required Packages by Using Project.json

Open the Project.cs file and modify its dependencies section as follows:

"dependencies": {
     "Microsoft.NETCore.App": {
      "version": "1.0.0-rc2-3002702",
      "type": "platform"
   },
   "Microsoft.AspNetCore.Mvc": "1.0.0-rc2-final",
   "Microsoft.AspNetCore.Razor.Tools": {
      "version": "1.0.0-preview1-final",
      "type": "build"
   },
   "Microsoft.AspNetCore.Server.IISIntegration":
      "1.0.0-rc2-final",
   "Microsoft.AspNetCore.Server.Kestrel": "1.0.0-rc2-final",
   "Microsoft.AspNetCore.StaticFiles": "1.0.0-rc2-final",
   "Microsoft.Extensions.Configuration.EnvironmentVariables":
      "1.0.0-rc2-final",
   "Microsoft.Extensions.Configuration.Json": "1.0.0-rc2-final",
   "Microsoft.Extensions.Configuration.Abstractions":
      "1.0.0-rc2-final",
   "Microsoft.AspNetCore.Http.Extensions": "1.0.0-rc2-final"
}

Especially notice the entries marked in bold letters. These assemblies are important for any ASP.NET Core 1.0 application. Also, ensure that the frameworks section matches the following:

"frameworks": {
   "netcoreapp1.0": {
      "imports": [
         "dotnet5.6",
         "dnxcore50",
         "portable-net45+win8"
      ]
   }
}

Once you modify the Project.json file, you may right-click the References folder in the Solution Explorer and click the Restore Packages option.

Configure the Application Startup

Now that you have added the required NuGet packages, let's configure the application startup. You do that by using the Startup class. So, open the Startup.cs file and add the following code to it:

public class Startup
{
   public Startup(IHostingEnvironment env)
   {
      var builder = new ConfigurationBuilder();
      builder.SetBasePath(env.ContentRootPath);
      builder.AddJsonFile("appsettings.json",
         optional: true, reloadOnChange: true);
      IConfiguration config = builder.Build();
   }

   public void ConfigureServices(IServiceCollection services)
   {
      services.AddMvc();
   }

    public void Configure(IApplicationBuilder app)
   {
      app.UseStaticFiles();
      app.UseMvc(routes =>
      {
         routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/
               {id?}");
      });
   }
}

The Startup class consists of a constructor and two methods: ConfigureServices() and Configure(). Let's examine them one by one.

The Startup constructor receives the IHostingEnvironment parameter through Dependency Injection. Inside, a ConfigurationBuilder object is created to read the application configuration file. The SetBasePath() method sets the base path where configuration files are located. In this case, ContentRootPath returns the physical path of the project root folder. AddJsonFile() adds an application configuration file that is in JSON format to the ConfigurationBuilder. In this case, we use AppSettings.json. You will create this file in the next section. Finally, the Build() method of ConfigurationBuilder is called to load the configuration settings into an IConfiguration object.

You will revisit the Startup constructor in the next section.

The ConfigureServices() method is automatically called by the ASP.NET Core framework and is intended to add the services required by the application. In this case, the AddMvc() method indicates that ASP.NET Core MVC 1.0 is to be used.

The Configure() method also is called automatically by the framework and is used to configure the HTTP pipeline. In this case, it calls the UseStaticFiles() method to enable the support for static files. It also calls UseMvc() to add MVC and also configures the default routing of the application.

Adding an Application Configuration File

Unlike ASP.NET, where an application's configuration is stored in the web.config file, ASP.NET Core uses a JSON file to store application configuration. An application's configuration includes things such as database connection strings and any application-specific pieces of information that you don't want to embed directly in the source code.

To add a configuration file, right-click the project root folder and select Add > New Item. Then, select the ASP.NET Configuration file (ensure that ASP.NET is selected in the left-hand side pane).

First4
Figure 4: Adding a configuration file

The default name given to this file is AppSettings.json. Once the file gets added to the project, open the file and add the following JSON markup into it:

{
   "MySettings": {
      "Title" :  "This is Website Title",
      "Email" :  "contact@localhost"
   },

   "Data": {
      "DefaultConnection": {
         "ConnectionString": "Server=(localdb)
            \\MSSQLLocalDB;Database=
            _CHANGE_ME;Trusted_Connection=True;"
      }
   }
}

The AppSettings.json file contains two sections: MySettings and Data. The MySettings section is important for our example because we will use it later. The MySettings section consists of two sub-keys, namely Title and Email. These keys hold the corresponding values, as shown in the markup.

There can be multiple ways to access these applications' settings in an application. Let's use a simplistic approach for our example. Add a class, named AppSettings, to your project and write the following code into it:

public class AppSettings
{
   public static string Title { get; set; }
   public static string Email { get; set; }
}

The AppSettings class consists of two static properties—Title and Email—to hold the respective values from the MySettings section.

Now, open the Startup class again and modify its constructor as shown below:

public Startup(IHostingEnvironment env)
{
   var builder = new ConfigurationBuilder();
   builder.SetBasePath(env.ContentRootPath);
   builder.AddJsonFile("appsettings.json", optional: true,
      reloadOnChange: true);
   IConfiguration config = builder.Build();
   AppSettings.Title = config["MySettings:Title"];
   AppSettings.Email = config["MySettings:Email"];
}

The above code reads the Title and Email keys under the MySettings section using the IConfiguration object. The Title and Email values then are assigned to the respective properties of the AppSettings class. Once assigned, you can read them anywhere in the application.

Adding Models, Views, and Controllers

Now, add three folders under the project root folder: Models, Views, and Controllers. These folders will hold the respective pieces of the application. Right-click the Models folder and select the Add > Class menu option. Name the class Employee and write the following code in it.

public class Employee
{
   public int EmployeeID { get; set; }
   public string FirstName { get; set; }
   public string LastName { get; set; }
}

The Employee class consists of three public properties, namely EmployeeID, FirstName, and LastName. Then, right-click the Controllers folder and open the Add New Item dialog. Add HomeController class to the project.

First5
Figure 5: Adding the HomeController class

Modify the Index() action of the HomeController as shown below:

public IActionResult Index()
{
   ViewBag.Title = AppSettings.Title;
   ViewBag.Email = AppSettings.Email;

   Employee emp = new Employee();
   emp.EmployeeID = 1;
   emp.FirstName = "Nancy";
   emp.LastName = "Davolio";

   return View(emp);
}

The Index() action sets two ViewBag properties, namely Title and Email, by reading the AppSettings class properties. It also creates an Employee object and assigns its property values. The Employee object is passed to the Index view as its model.

Now, add a Home subfolder under the Views folder and add a MVC view page to it.

First6
Figure 6: Adding a Home subfolder

Write the following HTML markup and Razor code in the Index view.

@model FirstAspNetCoreRC2Empty.Models.Employee

<html>
    <head>
      <title>Page Title</title>
   </head>
   <body>
      <h1>@ViewBag.Title</h1>
      <h2>Welcome @Model.FirstName @Model.LastName!</h2>
      <div>
         <strong>Contact : <a href="mailto:@ViewBag.Email">
            @ViewBag.Email</a></strong>
      </div>
   </body>
</html>

The above markup outputs the Title ViewBag property in the page heading. It also displays a welcome message using the Employee model object properties. An email link is displayed using the Email ViewBag property.

This completes the application. Run the application and see if it works as expected. Figure 7 shows a sample run of the application.

First7
Figure 7: Running the application

Download the Code

You can download the code that accompanies this article from this link.



Related Articles

Downloads

Comments

  • There are no comments yet. Be the first to comment!

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

Most Popular Programming Stories

More for Developers

RSS Feeds

Thanks for your registration, follow us on our social networks to keep up-to-date