This project is created to learn asp.net core web api
There is tutorial to create database for this project. If you want to skip, you can use database in PostAPI.Database folder.
The following is tutorial on how to create ASP.NET Wep API
-
Open Visual Studio
-
Click ASP .Net Core Web Application on New Project dialog
-
Select ASP .Net Core 2.2. If you don’t see the option, you may need to download .Net Core SDK 2.2 first. Download link : https://dotnet.microsoft.com/download/dotnet-core/2.2
-
Open SQL Server Management Studio
Run this script to create the databaseCREATE DATABASE Post USE [Post] GO /****** Object: Table [dbo].[Posts] Script Date: 6/17/2019 6:04:44 AM ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[Posts]( [Id] [uniqueidentifier] NOT NULL, [Title] [nvarchar](max) NOT NULL, [Content] [nvarchar](max) NULL, CONSTRAINT [PK_Posts] PRIMARY KEY CLUSTERED ( [Id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] GO
-
Check if the database is created.
You can check the design of created table Post by right click on table Post then click design

-
Click Tools -> NuGet Package Manager -> Package Manager Console

-
Run the following command
Scaffold-DbContext "Server=localhost;Database=Post;User Id=<user id>;Password=<password> " Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models
The command is used to generate database context and class model. The following is explanation of the command.
Server=localhost;Database=Post;User Id=<user id>;Password=<;password>
This is connection string to connect to database. You can read more about connection string here https://www.connectionstrings.com/sql-server/. You can use user id and password that is used to login to sql server.Microsoft.EntityFrameworkCore.SqlServer
This is database provider. This is library that is used to connect to database and generate class model. You can read more about class model here : https://docs.microsoft.com/en-us/ef/core/providers/indexOutputDir Models
Output directory where the database context and class model are generated. -
Open PostContext.cs then remove method **OnConfiguring.
We are going to add connection string configuration at Startup.cs -
To make the database context available to MVC controller, you have to register it first. Add this code to ConfigureServices method to register it.
services.AddDbContext<Models.PostContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
-
At the previous step, there is method to get connection strings DefaultConnection. We must add the connection string from appsettings.json. Open appsettings.json then add the connectionstring.

-
Build the project. Make sure it successfully built.
-
Remove the generated ValuesController.cs if any as we will not need it.

-
Right click on Controllers folder -> click Add -> click New Item

-
Select WebAPI Controller class -> name it PostController -> click Add. You can use filter to search Web API Controller Class menu item.

-
You will see the generated codes. We will use that as our base to create post api.

-
Decorate PostController with [ApiController] attribute (see screenshot). It will enable API-Specific behavior :
- Attribute routing requirement
- Automatic HTTP 400 responses
- Binding source parameter inference
- Multipart/form-data request inference
- Problem details for error status codes
You can visit this link for more information : https://docs.microsoft.com/en-us/aspnet/core/web-api/index?view=aspnetcore-2.2#apicontroller-attribute

-
Change PostController class inheritance to derive from ControllerBase class. Controller derives from ControllerBase and adds support for views, so it's for handling web pages, not web API requests. The ControllerBase class provides many properties and methods that are useful for handling HTTP requests. For example, ControllerBase.CreatedAtAction returns a 201 status code.
Source : [https://docs.microsoft.com/en-us/aspnet/core/web-api/index?view=aspnetcore-2.2#controllerbase-class]
(https://docs.microsoft.com/en-us/aspnet/core/web-api/index?view=aspnetcore-2.2#controllerbase-class) -
Add post context to post controller. Add this following code.
private PostContext _context; public PostController(PostContext context) { _context = context; }
-
We will use the generated method public void Post([FromBody]string value) decorated with [HttpPost] attribute

This method will receive Post value and return 201 status code, location header, and post data that is stored to database. HTTP 201 is the standard response for an HTTP POST method that creates a new resource on the server in tis case new post data stored to database. The location header specify the url of the new created post data.
Update Post method with this codepublic ActionResult<Posts> Post([FromBody]Posts postItem) { _context.Posts.Add(postItem); _context.SaveChanges(); return CreatedAtAction(nameof(Get), new { id = postItem.Id }, postItem); }

The CreatedAtAction method will return status code 201. The parameters are used to generate url to the newly stored data and to generate json of newly stored data. nameof(Get) is the method to get single post item (we will create this method later) and new {id = postItem.id} is the parameter to get the post item. -
We are going to test the method. Build and run the project. To test the api, you can use tools like Postman (https://www.getpostman.com/downloads/) or Advanced Rest Client (https://chrome.google.com/webstore/detail/advanced-rest-client/hgmloofddffdnphfgcellkdfbfbjeloo).
Details of the request :
**Url** :<hostname>/api/post <br/> **Method** :POST <br/> **Content-Type** :application/json <br/> **Body** :{"Id":"b67c7014-9d5b-4800-bda8-f0aa3523bc86","Title":"My First Post","Content":"Hello World !"} <br/>The response should be like this
-
We are going to use method public IEnumerable Get() to create method to retrieve all posts and method public string Get(int id) to create method to retrieve one post.
-
Update method IEnumerable Get() using the following codes :
public ActionResult<IEnumerable<Posts>> Get() { return _context.Posts; }
The method will return all post data. It will be in array of json object format. We will see what the json will be when we test the method.
-
Update method method public string Get(int id) using the following codes :
public ActionResult<Posts> Get(string id) { Guid postGuid = new Guid(); if (!Guid.TryParse(id,out postGuid)) return BadRequest(); var postItem = _context.Posts.Where(p => p.Id == postGuid); if (postItem.Count() == 0) return NotFound(); return postItem.SingleOrDefault(); }
This method will accept id as parameter. The expected parameter is guid. If not guid, this method will return bad request. If it’s guid, the method will return post item.
-
Build and run the project.
-
Now we are going to post both methods.
Testing Get Posts method (without parameter)
Details of the request :Url : <hostname>/api/post Method : GET Content-Type : application/jsonThe result should be like this. I’ve added few more items before.

-
Testing Get Posts method (with parameter)
Details of the request:Url : <hostname>/api/post/<post id> Method : GET Content-Type : application/json
-
To create method to update post, we will use method public void Put(int id, [FromBody]string value). This method uses HTTP PUT. The response is 204 (No Content). According to the HTTP specification, a PUT request requires the client to send the entire updated entity, not just the changes. To support partial updates, use HTTP PATCH.
-
Update method void Put(int id, [FromBody]string value) using this following code :
public ActionResult Put(string id, [FromBody]Posts postItem) { Guid postGuid = new Guid(); if (!Guid.TryParse(id, out postGuid)) return BadRequest(); if (postGuid != postItem.Id) return BadRequest(); _context.Entry(postItem).State = EntityState.Modified; _context.SaveChanges(); return NoContent(); }
-
Build the project.
-
Now we test the method.
Details of the request:
Url : <hostname>/api/post/e17a4da3-5cc3-4da7-a567-3ece2b3e4962 Method : PUT Content-Type : application/json Body : { "id": "e17a4da3-5cc3-4da7-a567-3ece2b3e4962", "title": "Emergency Exit is Gone !!!!", "content": "Apparently no one where it goes.” }If you check again using get post method, you will see that the content has been changed
-
We use HTTP DELETE to delete post. It will return 204 No Content. We use method
public void Delete(int id)to create delete post method. -
Update method public void Delete(int id) using the following code :
public ActionResult Delete(string id) { Guid postGuid = new Guid(); if (!Guid.TryParse(id, out postGuid)) return BadRequest(); var queryPostItem = _context.Posts.Where(p => p.Id == postGuid); if (queryPostItem.Count() == 0) return NotFound() var postItem = queryPostItem.SingleOrDefault(); _context.Posts.Remove(postItem); _context.SaveChanges(); return NoContent(); }
-
Build and run the project
-
Now we test the method.
Details of the request:Url : <hostname>/api/post/e17a4da3-5cc3-4da7-a567-3ece2b3e4962 Method : DELETE Content-Type : application/jsonIf you get all post data, you will see that the item does not in the list

















