Posts Contact Application Using ASP.NET Core Web API, Angular 6.0, And Visual Studio Code - Part One
Post
Cancel

Contact Application Using ASP.NET Core Web API, Angular 6.0, And Visual Studio Code - Part One

We will develop a contact application using ASP.NET Core Web API, Angular 6.0, and Angular Material UI as shown in the below screenshots.

contactapp

We will use Visual Studio code (VS code) for the development editor, I have divided contact application development into two articles:

So, Let’s start with this article, first, we will see how we can create ASP.Net Core Web API Project.

We have the following prerequisites:

  • Visual Studio Code (VS code) editor: Please see this article to see how we can setup Visual Studio code.
  • .Net Core: I have used .Net Core version 2.0.3 for this contact application. Please see this link from where we can download .Net Core SDK.

When .Net Core SDK is installed, we can check version from the console as shown in the screenshot:

contactapp

After this, we require VS code extensions that adds languages, debuggers, and tools to support our development workflow. Please see this article to see how we can manage extension in VS code.

We have added these extensions in VS code:

Now, we are ready for setup ASP.Net Core Web API project.

  • Open Command Prompt and enter the following commands:
    1
    2
    3
    
    mkdir contact-app  
    cd contact-app  
    dotnet new webapi 
    
  • Web API project has been created in the contact-app folder. Then go to the VS code, and open contact-app folder.
  • We can see one notification in the VS code’s right end corner. notification
  • Build and debugger tool has been set up in VS Code. debugger

  • Here now we are going to create the following API for the contact application:
APIDescriptionRequest bodyResponse body
GET - /api/contact/getAllContactGet all contactsNoneArray of to-do items
GET /api/contact/getContactGet contact ItemContact ItemContact Item
POST /api/contact/addContactAdd a new contactContact ItemContact Item
PUT /api/contact/updateContact{id}Update an existing contact itemContact itemNone
DELETE /api/contact/deleteContact{id}Delete an contact itemNoneNone

Create contact model

In this, we are creating a contact class that has getter-setter property as shown in snippet:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
public class Contact {  
    public long ? id {  
        get;  
        set;  
    }  
    public string name {  
        get;  
        set;  
    }  
    public string email {  
        get;  
        set;  
    }  
    public byte gender {  
        get;  
        set;  
    }  
    public DateTime ? birth {  
        get;  
        set;  
    }  
    public string techno {  
        get;  
        set;  
    }  
    public string message {  
        get;  
        set;  
    }  
}  

Create the database context for contact model

Here we are using a code-first approach to develop the contact application. So we have created ‘ContactAppContext’ class to communicate contact model to contact table.

1
2
3
4
5
6
7
public class ContactAppContext: DbContext {  
    public ContactAppContext(DbContextOptions < ContactAppContext > options): base(options) {}  
    public DbSet < Contact > Contact {  
        get;  
        set;  
    }  
}  

Register database context in startup:

To register database context we have followed these steps:

  • Go to “startup.cs” and update this code for SQL server connection in “ConfigureServices” method:
    1
    2
    
    services.AddDbContext<ContactAppContext>(options =>  
    options.UseSqlServer(Configuration.GetConnectionString("ContactDb"))); 
    
  • Then added “Microsoft.EntityFrameworkCore.SqlServer” Package in this project to support SQL server connection.

contactapp

Here we need to configure connection string in appsettings.json file as shown in the snippet.

1
2
3
"ConnectionStrings": {  
   "ContactDb": "Data Source=JAYESH-PC\\SQLEXPRESS;Initial Catalog=ContactDb;Integrated Security=True"  
}  

Initiate Database Migration

To create Initial migration script as per model, we enter “dotnet ef migrations add InitialCreate” command in VS code terminal and we get this issue:

databasemigration

To solve the issue we have to add this .Net Core CLI tool package in “contact-app.csproj” file and then enter “dotnet restore” in VS code terminal to restore these packages to create initial migration script:

  • Microsoft.EntityFrameworkCore.Tools
  • Microsoft.EntityFrameworkCore.Tools.DotNet datamigration

Now we enter “dotnet of migrations add InitialCreate” in VS code terminal and we can see that it will create migration folder and script “InitialCreate” in the project as shown in the screenshot: datamigration

Now update the database by entering “dotnet ef database update” command in VS code terminal and it will create a database in SQL server: datamigration Please see this article regarding .Net Core Migration.

Create contact API controller

After the database is ready, we have created API controller for CRUD operations as in the below snippet:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
// set route attribute to make request as 'api/contact'  
[Route("api/[controller]")]  
public class ContactController: Controller {  
    private readonly ContactAppContext _context;  
    // initiate database context  
    public ContactController(ContactAppContext context) {  
            _context = context;  
        }  
        [HttpGet]  
        [Route("getAllContact")]  
    public IEnumerable < Contact > GetAll() {  
            // fetch all contact records  
            return _context.Contact.ToList();  
        }  
        [HttpGet("{id}")]  
        [Route("getContact")]  
    public IActionResult GetById(long id) {  
            // filter contact records by contact id  
            var item = _context.Contact.FirstOrDefault(t => t.id == id);  
            if (item == null) {  
                return NotFound();  
            }  
            return new ObjectResult(item);  
        }  
        [HttpPost]  
        [Route("addContact")]  
    public IActionResult Create([FromBody] Contact item) {  
            // set bad request if contact data is not provided in body  
            if (item == null) {  
                return BadRequest();  
            }  
            _context.Contact.Add(new Contact {  
                name = item.name,  
                    email = item.email,  
                    gender = item.gender,  
                    birth = item.birth,  
                    techno = item.techno,  
                    message = item.message  
            });  
            _context.SaveChanges();  
            return Ok(new {  
                message = "Contact is added successfully."  
            });  
        }  
        [HttpPut("{id}")]  
        [Route("updateContact")]  
    public IActionResult Update(long id, [FromBody] Contact item) {  
            // set bad request if contact data is not provided in body  
            if (item == null || id == 0) {  
                return BadRequest();  
            }  
            var contact = _context.Contact.FirstOrDefault(t => t.id == id);  
            if (contact == null) {  
                return NotFound();  
            }  
            contact.name = item.name;  
            contact.email = item.email;  
            contact.gender = item.gender;  
            contact.birth = item.birth;  
            contact.techno = item.techno;  
            contact.message = item.message;  
            _context.Contact.Update(contact);  
            _context.SaveChanges();  
            return Ok(new {  
                message = "Contact is updated successfully."  
            });  
        }  
        [HttpDelete("{id}")]  
        [Route("deleteContact")]  
    public IActionResult Delete(long id) {  
        var contact = _context.Contact.FirstOrDefault(t => t.id == id);  
        if (contact == null) {  
            return NotFound();  
        }  
        _context.Contact.Remove(contact);  
        _context.SaveChanges();  
        return Ok(new {  
            message = "Contact is deleted successfully."  
        });  
    }  
}  
}  

Build and run contact application project

To build contact application project we have entered “dotnet build” command VS code terminal: datamigration

  • Setup development variable and URL for project in terminal:
    1
    2
    
    set ASPNETCORE_ENVIRONMENT=Development
    set ASPNETCORE_URLS=http://localhost:5000
    

    Then, to run project we have to enter “dotnet run”: datamigration

Please see this article for more information regarding .Net Core 2x commands.

Test API

  • To test API we have installed ChromeRestClient.
  • Then we have to open Rest Client, to get contact item by id we set HTTP parameter to get and request URL as shown in the below screenshot:

RestAPI

For adding contact item, we have set the body to contact JSON object:

RestAPI

Then, we request add contact URL and set HTTP parameter to post.

RestAPI

Conclusion

In this article, we learned about how we can develop ASP.Net Core Web API using VS code.

In the next article, we will learn about how we can set up Angular 6 in Web API Project and develop the contact list & contact form component using Angular Material UI. Please see this link for the Part-2 of this article.

Please see entire code in this GitHub https://github.com/JayeshAgrawal/contact-app.

Please share your feedback.