Build Your First ASP.NET MVC Core Application With Visual Studio Code

Introduction

ASP.NET core is a significant redesign of ASP.NET. ASP.NET core is an open source, cross platform framework to develop Cloud based applications like web applications, IoT applications, and mobile backend applications. We can develop and run the ASP.NET Core Application on multiple (cross) platforms such as Windows, Mac OS and Linux.

Visual Studio code is a light weight source code editor developed by Microsoft, which supports multi OS platform like Windows, Linux and iOS. This editor is helpful in coding and debugging. It also includes intelligent code completion, snippets, code refactoring, embedded Git control and syntax highlighting. There are many extensions available and using these extensions, it is able to support the multiple languages like C#, C++, Objective C, Perl, R, Ruby, Python VB, etc.

In this article we will learn how to create MVC Application in .NET core, using VS code. Following are the steps to create MVC Application in .NET Core. using VS code.

Step 1- Create new dot net core application

Using the following command, we can create new .NET Core Application. It can be either Web or desktop. The "dotnet" is a general driver to run the commands on CLI (Command Line Interface). Visual studio code works well with other tools like command-line tool. We can also run "dotnet" command, using command prompt.

>dotnet new

When we run the command, shown above, it creates an empty project. The empty project mainly contains two files, which are program.cs and project.json.

contains

Program.cs file have default method called "Main". This method is an entry point for the Application. Project.json file contains the information like version of .NET Core framework, compilation options, framework details, dependencies, script for installing front-end dependencies etc.

Adding Kestrel web server dependency to Project.json
ASP.NET Core is designed to host the web application from the HTTP server. Older ASP.NET Application were hosted only on IIS. For ASP.NET Core, the recommended way is to run apps on IIS for Windows Server but as a reverse proxy. Kestrel is a lightweight and fast cross-platform Web Server, which can be used to self-host our Web Application. It can help to run our Application without relying on IIS or IIS Express.

  1. {  
  2.     "version": "1.0.0-*",  
  3.     "buildOptions": {  
  4.         "debugType": "portable",  
  5.         "emitEntryPoint": true  
  6.     },  
  7.     "dependencies": {},  
  8.     "frameworks": {  
  9.         "netcoreapp1.0": {  
  10.             "dependencies": {  
  11.                 "Microsoft.NETCore.App": {  
  12.                     "type": "platform",  
  13.                     "version": "1.0.0"  
  14.                 },  
  15.                 "Microsoft.AspNetCore.Server.Kestrel": "1.0.0"  
  16.             },  
  17.             "imports": "dnxcore50"  
  18.         }  
  19.     }  
  20. }  
Step 2 - Restores the dependencies

Using "dotnet restore" command, we can restore the dependencies which are used by the project.

>dotnet restore

{ "version": "1.0.0-*", "buildOptions": { "debugType": "portable", "emitEntryPoint": true }, "dependencies": {}, "frameworks": { "netcoreapp1.0": { "dependencies": { "Microsoft.NETCore.App": { "type": "platform", "version": "1.0.0" }, "Microsoft.AspNetCore.Server.Kestrel": "1.0.0" }, "imports": "dnxcore50" } } }

When we run the "dotnet restore" command, it will restore the packages to the default location (%userprofile%\.nuget\packages).

Now, I am opening my Application in Visual Studio code.

{ "version": "1.0.0-*", "buildOptions": { "debugType": "portable", "emitEntryPoint": true }, "dependencies": {}, "frameworks": { "netcoreapp1.0": { "dependencies": { "Microsoft.NETCore.App": { "type": "platform", "version": "1.0.0" }, "Microsoft.AspNetCore.Server.Kestrel": "1.0.0" }, "imports": "dnxcore50" } } }

As we know, VS code works with multiple languages and by default, VS Code is a simple editor, not language specific. To support the language, there are many extensions available. Here, I am going to create an Application, using C# language, so I have downloaded the C# extension.



Visual Studio code provides the option to create files and folders. Following snap illustrate, there are four options, which are available when your mouse hovers on project folder.

{ "version": "1.0.0-*", "buildOptions": { "debugType": "portable", "emitEntryPoint": true }, "dependencies": {}, "frameworks": { "netcoreapp1.0": { "dependencies": { "Microsoft.NETCore.App": { "type": "platform", "version": "1.0.0" }, "Microsoft.AspNetCore.Server.Kestrel": "1.0.0" }, "imports": "dnxcore50" } } }

Step 3 - Configure your web application to use MVC

The startup class provides the entry point for all the Application in .NET code. The startup class may optionally accept dependencies in the class constructor. The startup class must have "Configure" method, and may optionally have a "ConfigureServices" method when the application is started.

The configuration method of the Startup file is used to tell the ASP.NET Application, how it will respond to individual HTTP requests. In the following code, I just tell our Application to return a response and write the text “Hello Readers!” to it.

Startup.cs
  1. using Microsoft.AspNetCore.Builder;  
  2. using Microsoft.AspNetCore.Http;  
  3.   
  4. namespace ConsoleApplication {  
  5.     public class Startup {  
  6.         public void Configure(IApplicationBuilder app) {  
  7.             app.Run(context => {  
  8.                 returncontext.Response.WriteAsync("Hello Readers!");  
  9.             });  
  10.         }  
  11.     }  
  12. }  
Now, I have told my Application to start Kestrel and when Kestrel starts, it starts to accept the Web request. This is done by following the code, given below, in Program.cs-

Program.cs
  1. using System.IO;  
  2. using Microsoft.AspNetCore.Hosting;  
  3.   
  4. namespace ConsoleApplication {  
  5.     public class Program {  
  6.         public static void Main(string[] args) {  
  7.             var host = new WebHostBuilder()  
  8.                 .UseKestrel()  
  9.                 .UseContentRoot(Directory.GetCurrentDirectory())  
  10.                 .UseStartup < Startup > ()  
  11.                 .Build();  
  12.   
  13.             host.Run();  
  14.         }  
  15.     }  
  16. }  
At this point, our Application is ready to run Let test in Browser. To run the Application, we can either use VS code debugger or "dotnet run" command. Currently, I am using "dotnet run" command to run the Application.

The "dotnet run" command runs the project in the current directory and the hosted Application on default 5000 port.

> dotnet run


Output 



To convert out Web Application to MVC, we need to add MVC package in to project.json.

Microsoft.AspNetCore.Mvc": "1.0.0

using System.IO; using Microsoft.AspNetCore.Hosting; namespace ConsoleApplication { public class Program { public static void Main(string[] args) { var host = new WebHostBuilder() .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) .UseStartup < Startup /> () .Build(); host.Run(); } } }

Here, we had added new dependency of MVC package, so we need to run "dotnet restore" command to download this dependency to the machine.

The ConfigureServices method of Startup class is used to configure the Services, which can be used by the Application. This method is called before the "Configure" method because some of the features like MVC are required to add some Service in this method before system can be wired up for the request pipeline.

The app.UseMvc() method is used to tell the Application, which adds MVC to the request execution pipeline and this function ensures that all the requests to the Web Application are routable to the MVC framework.
  1. using Microsoft.AspNetCore.Builder;  
  2. using Microsoft.AspNetCore.Http;  
  3. using Microsoft.Extensions.DependencyInjection;  
  4.   
  5. namespace ConsoleApplication {  
  6.     public class Startup {  
  7.         public void ConfigureServices(IServiceCollection services) {  
  8.             services.AddMvc();  
  9.         }  
  10.         public void Configure(IApplicationBuilder app) {  
  11.             app.UseMvc();  
  12.             app.Run(context => {  
  13.                 return context.Response.WriteAsync("Hello Readers!");  
  14.             });  
  15.         }  
  16.     }  
  17. }  
Step 4 - Adding Controller and View to our application

In this step, I have added a folder called "Controllers" and within this, add HomeController.cs file. I have also created a folder called "Views" and add all the views related to HomeController into this folder. As we know, MVC has its own folder structure, we need to follow the folder structure here as well.

Adding Controller and View to our application

Here, I am using an attribute routing because it is simplest way to get started. Following definition for controller class, here I have created an index action method and from this method, I will just return an index view.

HomeController.cs
  1. using Microsoft.AspNetCore.Mvc;  
  2.   
  3. public class HomeController: Controller {  
  4.     [Route("home/index")]  
  5.     public IActionResult Index() {  
  6.         return View();  
  7.     }  
  8. }  
In the view, I have just added simple text "Hello Article Reader! Enjoy!!!".

Index.cshtml
  1. <div>  
  2. <h1>Hello Article Reader! Enjoy!!!</h1>  
  3. </div>  
To run our Application, we need to do some setting into the Project.json and progrom.cs files. We need to add preserveCompilationContext to project.json file to ensure that various reference assemblies are preserved, so that Core can compile our Razor views at the runtime.

We also need to tell Core Application from where to start looking for the content files like views. Thus, we need to define this setting, using UseContentRoot method in program.cs file.



Output


 
Finally, we have successfully created view and controller and when we run our Application, it gives an expected result.

Now, let's pass some data from controller to view, using model. For it, I have created folder called "Model" and created User class within this folder.

User.cs
  1. public class User {  
  2.     public string UserName {  
  3.         get;  
  4.         set;  
  5.     }  
  6.     public int UserId {  
  7.         get;  
  8.         set;  
  9.     }  
  10. }  


To demonstrate, I have created one new action method to HomeController called "ViewUserData". This action method passes the user name to view, using User class. I have also created a respected view.

HomeController.cs
  1. [Route("home/ViewUserData")]  
  2. public IActionResult ViewUserData() {  
  3.     User u = new User();  
  4.     u.UserName = "Jignesh";  
  5.     return View(u);  
  6. }  
ViewUserData.cshtml
  1. <div>  
  2.     <h2>Hello @Model.UserName</h2>  
  3.     <h3>WelCome to C# corner!</h3>  
  4. </div>  
Output

Output

Summary - In this article, we learned how to create MVC Application, using .NET Core Framework. There is a minor difference between Web Application and MVC Applications as MVC Application has some special configuration.