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.
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 will use Visual Studio code (VS code) for the development editor.
I have divided contact application development into two articles,
- Contact Application using ASP.NET Core Web API, Angular 6.0, and Visual Studio Code Part – 1
In the article, we will set up ASP.NET Core Web API project, and develop the Web API controller for contact CRUD operations. - Contact Application using ASP.NET Core Web API, Angular 6.0, and Visual Studio Code Part – 2
In the article, we will setup Angular 6 within ASP.NET Core Web API Project, and develop the contact form & list component using Angular Material UI.
So, starting with this article, first, we will see how we can create ASP.Net Core Web API Project.
We have the following prerequisites,
When .Net Core SDK is installed, we can check version from the console as shown in the screenshot:
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:
- ASP.NET core VS Code Extension Pack
- .NET Core Extension Pack
- Angular v6 Snippets
- Angular 6 Snippets - TypeScript, Html, Angular Material, ngRx, RxJS & Flex Layout
- Open Command Prompt and enter the following commands,
- 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.
- Build and debugger tool has been set up in VS Code.
Here now we are going to create the following API for the contact application:
Create the database context for contact model
Here we need to configure connection string in appsettings.json file as shown in the snippet.
Build and run contact application project
API
|
Description
|
Request body
|
Response body
|
GET
/api/contact/getAllContact
|
Get all contacts
|
None
|
Array of to-do items
|
GET
/api/contact/getContact
|
Get contact Item
|
Contact Item
|
Contact Item
|
POST
/api/contact/addContact
|
Add a new contact
|
Contact Item
|
Contact Item
|
PUT
/api/contact/updateContact{id}
|
Update an existing
contact item
|
Contact item
|
None
|
DELETE
/api/contact/deleteContact{id}
|
Delete an contact
item
|
None
|
None
|
Create contact model
In this, we are creating a contact class that has getter-setter property as shown in snippet,
- 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;
- }
- }
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.
- 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,
- services.AddDbContext<ContactAppContext>(options =>
- options.UseSqlServer(Configuration.GetConnectionString("ContactDb")));
Then added ‘Microsoft.EntityFrameworkCore.SqlServer’ Package in this project to support SQL server connection.
Here we need to configure connection string in appsettings.json file as shown in the snippet.
- "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:
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
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:
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:
- // 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."
- });
- }
- }
- }
To build contact application project we have entered ‘dotnet build’ command VS code terminal,
Setup development variable and URL for project in terminal:
- set ASPNETCORE_ENVIRONMENT=Development
- set ASPNETCORE_URLS=http://localhost:5000
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:
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 of the Part-2 article.
Please see entire code in this GitHub link.
Please share your feedback.
Thank you for sharing this wonderful article.
ReplyDelete