Written by Andrei MoraruNov 14, 2019

Introduction

Building your own website from scratch is easy they said. That would be true if there weren't so many things that make you bang your head against the wall in one of the first phases of a web site development lifecycle.

In this article, I'm going to show you how to set up your computer in order to be able to build your own website using the .NET Framework and Angular. The approach I'm going to use is to have separate projects for your backend and frontend. In other words, we are going to have a backend API that is going to be used by our frontend project in order to display stuff and perform any and all operations.

As a brief recap, when we use the term backend, we refer to any and all operations performed on the server where the app is hosted. When we use the term frontend, we refer to any and all code and operations that are executed in the browser. So, without further ado, let's kick this into 1st gear.

Setting up the backend project

The .NET Framework I have mentioned is a framework that makes use of the C# programming language and it was developed by Microsoft. Regardless of the programming language you choose to write your code in though, the first and most important program you'll need is one that will allow you to write code in the language of your choice and which will help you compile and build the code into a fully functioning application.

That is why, the first thing we need to do is install Visual Studio, the Community Edition. For that, simply visit this website, select Community Edition, download and install it. When installing, you will be asked to select some options and components which will define what types of projects you can create. I usually leave them set to default. If you know you want a certain framework version or whatnot, feel free to select or deselect the options to fit your desire.

Anyhow, now that we have our lovely IDE (which stands for Integrated Development Environment) installed, let's actually create a project and configure it. So, let's open Visual Studio. You should be greeted with a window that looks something like the picture below. Select Create a new project:

 

 

Then, you should be greeted with a window that looks like the picture below:

 

 

Now, in the Search area in the right part of the screen, write Web Application. A bunch of options will appear. Make sure you select ASP.NET Web Application (.NET Framework). Afterward, you will be greeted by a window that allows you to enter a name for your solution, as well as a folder in which to store it. It should look something like this:

 

 

Enter whatever name you like and click Create. Afterward, you should see a window in which you select the application type. Select Empty, tick the Web API option on the right and click Create:

 


 

As you will now see, a project has been created for you with a certain structure. Notice the App_Start folder. Inside it, there is a WebApiConfig.cs file, which contains instructions about how your web API is to be configured. We're going to edit that file in just a few moments.

Also, notice the Global.asax file. That file is vital to remember because it is basically the place where you define what methods are run when your app is started. As you can see, we use the Register method from the WebApiConfig.cs file.

Now, let's to a bit of NuGet package management. From the Solution Explorer on your right, right-click on the solution name and click Manage NuGet packages for Solution... :

 




 

Now, in the Browse tab, search for the following packages and install them:

·        Microsoft.AspNet.Cors - I used the latest stable version for it (5.2.7 as of writing this)

·        Microsoft.AspNet.WebApi.Cors - also the latest version (5.2.7 as of writing this)

Now, let's modify the WebApiConfig.cs file in order to configure our project as a proper REST API that allows requests from outside websites as well:

public static void Register(HttpConfiguration config)

{

               // Web API configuration and services

               var cors = new EnableCorsAttribute(

                              "*", // allowed websites

                              "*", // allowed headers

                              "*"); // allowed methods

               config.EnableCors(cors);

 

               // JSON camel case

               config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();

               config.Formatters.JsonFormatter.UseDataContractJsonSerializer = false;

 

               // Web API routes

               config.MapHttpAttributeRoutes();

 

               config.Routes.MapHttpRoute(

                              name: "DefaultApi",

                              routeTemplate: "api/{controller}/{id}",

                              defaults: new { id = RouteParameter.Optional }

               );

}

 Now, let's take a moment to explain a few things. So, first off, we needed to install some packages that were related to something called Cors. Cors is an acronym for Cross Origin Request Strategy and is used for scenarios when two websites or applications need to communicate with one another.

In our scenario, we will have two distinct apps. And while they will most definitely be hosted on the same hard drive on a server somewhere, they will run on different ports. And, for all intents and purposes, they will act as two different applications, even though the server is the same.

Cors is a way in which you can tell our REST API what other websites it should allow requests from. Now in this example, we have used the * wildcard, which basically means that it allows requests from anyone. In a production environment, you will most definitely provide a website or a list of websites. You can provide multiple websites by separating them with a comma. Just make sure you pass those websites as a singular string containing them all, separated by commas.

The second part of the configuration is optional. However, coding conventions may make life difficult. C# coding conventions say that you have to name your variables by using Pascal Case, which means starting each word with a capital letter (for example, CarName). Angular, however, is a framework written in Typescript, which uses the camel case convention, which tells you your variables by starting with a lower case letter and then use an upper case for any other words (for example, carName).

That whole ContractResolver the configuration is in place to make sure that, when supplying the results from an API call, C# will convert it from Pascal case to camel case.

The final two pieces of configuration are used to help your web API process requests and redirect them to the appropriate controller.

You can now build your backend application by using the Ctrl+Shift+B command and run it by using the Ctrl+F5 command or F5 if you want to run it in Debug mode. As you can see, it will load on your localhost on what seems like a random port number. You can actually see this number in your project. Right-click on the project located inside your solution and select Properties:

 

 

Go to the Web tab on the left and you'll see the launch URL. This URL will come in handy in the next section.

Setting up the frontend project

Now that we have a backend API (which by the way stands for Application Programming Interface) set, it's time to create the project for the website itself. For that, we need to install two things:

·        Visual Studio Code, a very useful IDE, which is found here

·        Node JS, which also installs the node package manager, which is found here

Once that is done and dusted, you can create a folder anywhere on your hard drive (say D:\Projects). Navigate to that folder and in the address bar of its window, type cmd and press Enter. It should open a command prompt which already has its location set in this current folder. Now, we need to use the node package manager (or npm) to install the Angular command-line interface, which is a great deal of help for when you want to build websites using this framework. For that, run the following command:

npm install -g @angular/cli

This will install the CLI globally (hence the -g), which means that you can use it from anywhere on your computer.

After the installation is finished, let's create the Angular project by running the following command:

ng new my-website

Angular will ask you the type of styling you want to use (css, scss or less). Choose whatever you want and voila, you now have your Angular app ready to go. In order to check it out, you need to navigate to the folder of the app:

cd my-website

Inside that folder, run this command:

ng serve --open

The app should open shortly.

Before we leave, there is one final bit of configuration we need to do. Since we are using an external API, which runs on a different port, we need to tell Angular that. Otherwise, we'll just get a bunch of 404 requests anytime we try to call said API.

Let's open Visual Studio Code. If it asks you to open something, select Open Folder and select the folder which was generated via the ng new command. In the left part of the VS Code window, you'll see the project structure. Right click in there, select New File and name it proxy.conf.json. Inside it, place the following code:

{ 

    "/api/*": { 

       "target": "http://localhost:44339", 

       "secure": false, 

       "logLevel": "debug" 

    } 

 }

What this does is intercept any request that starts with api/ and redirects it to the specified target. We now need to reference this proxy file in angular.json. Open it, search for the serve config block and modify the options block by adding a proxyConfig to this file:

"options": {

        "browserTarget": "my-website:build",

        "proxyConfig": "proxy.conf.json"

}

And yeah, those are the necessary steps required to configure your environment for website development. Now, get to coding and I hope you have found this article helpful.

Andrei Moraru, Senior Software Engineer @Upstack

Andrei Moraru: "I am a skilled Software Developer with 6+ years of hands-on expertise and specialty in the development of cutting-edge full-stack solutions using the latest tools and tech stacks on projects for clients. I have cultivated a learning attitude, exceptional work ethic and excellent customer service on the job - offering clients high-quality solutions that meet the latest industry standards."

Andrei is the type of developer who is continuously learning and improving his skills.

P.S.: Take a look at Andrei's site too -> When programming and music meet! You'll discover some really cool content there. 

 

At Upstack we help you grow your business faster. We connect you with the top 1% developers in the world.

Contact us NOW!