Set up new Project with .Net Core and Angular 9
By: Praveen Sambu
Tags: UI, Net Core, Rest, Angular

Integrating Angular 9 with .Net Core Rest API is fun part. In this article I would share how we can do that.

I have been reading lot of blogs and when I see people only sticking to front end or back end as they lack knowledge on the projects integrate. Here is my detailed guide on how we can integrate front end and back end.

Creating a Rest API for Angular with .Net Core

similar to Node.Js, we have .Net Core to implement server side architecture.we need to have them as two separate projects to loosely couple solutions to get benefit of .Net Core. As same Rest API can be consumed by various kinds of clients.

Lets Start…

In order to create .Net core project, create folder in c:\ and open command prompt/power shell inside that folder and type below command

dotnet new webapi -o {name-of-your-project}

Replace the {} placeholder. E.g.

dotnet new webapi -o myFirstProject

this would automatically create a new project for you and you could see the project related files under the folder. Lets go with each file to know why we use them

Program.cs

This file contains the entry point of our application. Every C# program starts with a static method called Main. We can find that method in the class Program inside of this file. All it does is calling the BuildWebHost method. It is responsible to configure and start the server-app. Quite similar to angular’s bootstrap method.

public class Program

{

public static void Main(string[] args)

{

BuildWebHost(args).Run();

} public static IWebHost BuildWebHost(string[] args) =>

WebHost.CreateDefaultBuilder(args)

.UseStartup<Startup>()

.Build();

}

There is already some configuration going on here. As you can see, the builder is told to use the class Startup, to configure our app. We will take a look at that class next.

Startup.cs

The Startup class is the main configuration file of your class. Here, we add features and services to our server.

The class does contain two methods. The first one is called ConfigureServices.

public void ConfigureServices(IServiceCollection services)

{

services.AddMvc();

}

This method is called by the runtime, Inside of this method, we add certain services to the services collection passed into the method.

These services can then be requested via dependency injection in our classes constructors. In that way, it is very similar to angular, because both use dependency injection systems. Instead of adding our services to the provider-property of our module, we add it to the provided service-collection.

By default, the MVC-Service (Model-View-Controller) is added. This service is responsible for routing the HTTP-requests to our controllers. Although we do not require a view, we need to use this service for our controllers to work.

The second method is the called Configure. It gets an IApplicationBuilder-instance and the current environment.

public void Configure(IApplicationBuilder app, IHostingEnvironment env)

{

if (env.IsDevelopment())

{

app.UseDeveloperExceptionPage();

} app.UseMvc();

}

With this application-builder, we can add middleware to our HTTP-request pipeline. Every request is going through this pipeline. For example, we want to show an exception page, if there was an error in any request. We only want to show that, when in development mode, to not leak any sensible information.

Finally, the last element of our HTTP-pipeline is the MVC-middleware. It is responsible for forwarding the requests to the responsible controller.

Controllers

The “Controllers” folder does contain all of our servers controllers. Surprise!

That folder has to be named exactly like this because the MVC-middleware is explicitly looking for this folder.

What is a Controller?

A controller is just a class that inherits from the Controller class. It is responsible for handling the request of a certain route. There is typically one controller for every REST-endpoint, we want to create.

For example, if you want a “User”-endpoint, we would create a User-controller that would be responsible for the route “api/User”.

The dotnet-cli has already created a controller for us called “ValuesController”. The thirst thing a typically do within a new project is to delete that controller, but it can be useful to keep it around as a reference when you are getting started.

Creating our first Controller

To create our User-endpoint, we will need to create our first controller. To do so, we create a new file inside of the controller-directory called “UserController.cs”. Again, if you are using Visual Studio, there is a fancy template for that.

Our controller consists of a class called UserController. It is decorated by a so-called attribute (Route), that is telling the framework, which route this controller is responsible for. Attributes are similar to the decorators in angular/TypeScript, as they add meta information to the class.

using Microsoft.AspNetCore.Mvc; namespace firstProjectWebApi.Controllers

{

[Route("api/[controller]")]

public class UserController : Controller

{ }

}

In this example, the controller would be listening for request at the route “api/user”. The “[controller]” part is replaced by the name of the controller by the framework. This only works if you follow the naming convention {name}Controller.

An equivalent attribute would be this:

[Route("api/user")]

“REST-API”? Can you eat that?

As I told you already, we are going to create a REST-API. But what is that exactly? Let’s find out!

I will try to keep this short: REST is a standardized way of building HTTP-endpoints.

It uses the standard HTTP-verbs like get, post, put & delete to express read, create update & delete (CRUD) operations.

All these methods (verbs) are applied to one endpoint, which represents the object to be modified. This has an object-oriented touch to it,

For example, if I wanted to modify a user in any way, the endpoint would be named “user”.

Here is how the CRUD operations are modeled.

CRUD Operations

Create: To create a new object under an endpoint, a post-request is sent to the REST-endpoint containing the new object to create in the post-body.

Read(GET): To read all objects from an endpoint.

Create(POST): In order to create a new object under an endpoint, a post-request is sent to the REST-endpoint containing the new object to create in the post-body.

Update(PUT): To update an object, a put request is sent to the endpoint.

Delete(Delete): To delete an object, a delete request is sent to the endpoint with the identifier of the wanted object added to the route.

A typical REST-Endpoint does implement all the CRUD-operations listed above.

Because C# is strongly typed, we need to create a model first. To do that, create a new folder called “Models” inside of the projects root directory. Inside of that new folder, create a new class-file called “User.cs”.

namespace firstProjectWebApi.Models

{

public class User

{

public string Name { get; set; }

}

}

Sample REST API End points

Fetching All Users

[HttpGet]

public IEnumerable<User> GetAll()

{

var list = new List<User>();

list.Add(new User() { Name = "Lilly" });

list.Add(new User() { Name = "Lucy" });

return list;

} [HttpGet("{name}")]

public User Get(string name)

{

return new User() { Name = name };

} Inserting a New Element

[HttpPost]

public User Insert([FromBody]User user)

{

// write the new user to database

return user;

}

//Updating an existing Element [HttpPut("{name}")]

public User Update(string name, [FromBody]User user)

{

user.Name = name;

// write the updated user to database

return user;

} //Deleting an Element

[HttpDelete("{name}")]

public void Delete(string name)

{

// delete the user from the database



}

Consuming our ASP.NET Core REST-API in an Angular Application

In order to create a new application I believe go through the below link to create new angular application.

What is Angular?

Let’s see, what the angular developers have to say about that:

Single Page Applications

Basically, when people talk about Angular, they talk about it as a JavaScript framework. It is used to build so-called Single Page Applications (SPA). These SPA’s typically (but not only) use the browsers JavaScript environment to emulate the behavior of normal websites

Hope You have installed Node and Angular CLI installed in your machine.

check that by Node -v and ng-v