In Focus

Create Rest API Or Web API With ASP.NET Core 1.0

In this article, I will explain how to create Rest API or Web API with ASP.NET Core 1.0, starting from scratch.

Introduction 
 
There are several articles on Google for creating Rest API or Web API with ASP.NET Core 1.0. In this article, I will explain how to create Rest API or Web API with ASP.NET Core 1.0, starting from scratch.
 
Before reading this article, you must read the articles given below for ASP.NET Core knowledge.
Start from Scratch
 
We choose "Empty" template in "ASP.NET Core Templates" Category. I think someone may have a doubt like -- without selecting a "Web API", why do we choose "Empty" template in "ASP.NET Core Templates" Category ? Because the "Web API" templates automatically generate a few libraries related to REST API creation. So, we don’t know what is happening in the background. That’s why we choose "Empty" template. 
 
 
 
References Required 
 
We need the following references for accessing Static files, libraries for Routing, and Rest API, accessing MVC design pattern, etc.
  1. "Microsoft.AspNetCore.StaticFiles""1.1.0",  
  2. "Microsoft.AspNetCore.Routing""1.0.1",  
  3. "Microsoft.AspNetCore.Mvc.Core""1.0.1",  
  4. "Microsoft.AspNetCore.Mvc.ViewFeatures""1.0.1",  
  5. "Microsoft.AspNetCore.Mvc""1.0.1"  
Project.json
 
The following JSON file will show the full reference structure of our Web API application. 
  1. {  
  2.   "dependencies": {  
  3.     "Microsoft.NETCore.App": {  
  4.       "version""1.0.1",  
  5.       "type""platform"  
  6.     },  
  7.     "Microsoft.AspNetCore.Diagnostics""1.0.0",  
  8.     "Microsoft.AspNetCore.Server.IISIntegration""1.0.0",  
  9.     "Microsoft.AspNetCore.Server.Kestrel""1.0.1",  
  10.     "Microsoft.Extensions.Logging.Console""1.0.0",  
  11.     "Microsoft.AspNetCore.StaticFiles""1.1.0",  
  12.     "Microsoft.AspNetCore.Routing""1.0.1",  
  13.     "Microsoft.AspNetCore.Mvc.Core""1.0.1",  
  14.     "Microsoft.AspNetCore.Mvc.ViewFeatures""1.0.1",  
  15.     "Microsoft.AspNetCore.Mvc""1.0.1"  
  16.   },  
  17.    
  18.   "tools": {  
  19.     "Microsoft.AspNetCore.Server.IISIntegration.Tools""1.0.0-preview2-final"  
  20.   },  
  21.    
  22.   "frameworks": {  
  23.     "netcoreapp1.0": {  
  24.       "imports": [  
  25.         "dotnet5.6",  
  26.         "portable-net45+win8"  
  27.       ]  
  28.     }  
  29.   },  
  30.    
  31.   "buildOptions": {  
  32.     "emitEntryPoint"true,  
  33.     "preserveCompilationContext"true  
  34.   },  
  35.    
  36.   "runtimeOptions": {  
  37.     "configProperties": {  
  38.       "System.GC.Server"true  
  39.     }  
  40.   },  
  41.    
  42.   "publishOptions": {  
  43.     "include": [  
  44.       "wwwroot",  
  45.       "web.config"  
  46.     ]  
  47.   },  
  48.    
  49.   "scripts": {  
  50.     "postpublish": [ "dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" ]  
  51.   }  
  52. }  
Project Structure
 
This is the project structure of our Rest API application. 
 
Picture Source : https://rajeeshmenoth.wordpress.com 
 
LibraryDetails.cs 
 
We have created the following class for property details in our Rest API application.
  1. namespace DotNetCoreExtentions  
  2. {  
  3.     public class LibraryDetails  
  4.     {  
  5.         public int Id { getset; }  
  6.         public string Author { getset; }  
  7.         public string BookName { getset; }  
  8.         public string Category { getset; }  
  9.            
  10.     }  
  11. }  
API Controller
 
We have to create one folder named  "Controllers". Right click on the "Controllers" folder and go to the following steps to create an API class "Add – > New item.. -> Web API Controller Class"
 
We have created an API Class named as "LibraryAPI".
 
LibraryAPI.cs
 
The following code contains the CRUD operation of REST API application.
  1. using System.Collections.Generic;  
  2. using System.Linq;  
  3. using Microsoft.AspNetCore.Mvc;  
  4. using Microsoft.AspNetCore.Routing;  
  5.    
  6. // For more information on enabling Web API for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860  
  7.    
  8. namespace DotNetCoreExtentions  
  9. {  
  10.     [Route("api/[controller]")]  
  11.     public class LibraryAPI : Controller  
  12.     {  
  13.         LibraryDetails[] LibraryDetails = new LibraryDetails[]  
  14.         {  
  15.             new LibraryDetails { Id=1, BookName="Programming C# for Beginners", Author="Mahesh Chand", Category="C#" },  
  16.             new LibraryDetails { Id=2, BookName="Setting Up SharePoint 2016 Multi-Server Farm In Azure", Author="Priyaranjan K S", Category="SharePoint" },  
  17.             new LibraryDetails { Id=3, BookName="SQL Queries For Beginners", Author="Syed Shanu", Category="Sql" },  
  18.             new LibraryDetails { Id=4, BookName="OOPs Principle and Theory", Author="Syed Shanu", Category="Basic Concepts" },  
  19.             new LibraryDetails { Id=5, BookName="ASP.NET GridView Control Pocket Guide", Author="Vincent Maverick Durano", Category="Asp.Net" }  
  20.         };  
  21.            
  22.         // GET: api/values  
  23.         [HttpGet]  
  24.         public IEnumerable<LibraryDetails> GetAllBooks()  
  25.         {  
  26.             return LibraryDetails;  
  27.         }  
  28.    
  29.         // GET api/values/5  
  30.         [HttpGet("{id}")]  
  31.         public IActionResult Get(int id)  
  32.         {  
  33.             var books = LibraryDetails.FirstOrDefault((p) => p.Id == id);  
  34.    
  35.             var item = books;  
  36.             if (item == null)  
  37.             {  
  38.                 return NotFound();  
  39.             }  
  40.             return new ObjectResult(item);  
  41.         }  
  42.            
  43.         // POST api/values  
  44.         [HttpPost]  
  45.         public void Post([FromBody]string value)  
  46.         {  
  47.         }  
  48.    
  49.         // PUT api/values/5  
  50.         [HttpPut("{id}")]  
  51.         public void Put(int id, [FromBody]string value)  
  52.         {  
  53.         }  
  54.    
  55.         // DELETE api/values/5  
  56.         [HttpDelete("{id}")]  
  57.         public void Delete(int id)  
  58.         {  
  59.         }  
  60.     }  
  61. }  
[Route("api/[controller]")]
 
The route will assign a single route path for accessing specific API Controller CRUD operations. Instead of "[controller]", we can mention our controller name as "LibraryAPI" in client side or server side code. If searching for any information from API, we can pass id like this -"api/LibraryAPI/id". 
 
Accessing JSON data into Library API
 
At client-side, we are going to access JSON data from Library API with the help of JavaScript.
  1. //api url  
  2.         var uri = 'api/LibraryAPI';//[Route("api/[controller]")] instead of [controller] we can mention our API classname.  
  3.    
  4.         $(document).ready(function () {  
  5.             // Send an AJAX request  
  6.             $.getJSON(uri)  
  7.                 .done(function (data) {  
  8.                     // On success, 'data' contains a list of products.  
  9.    
  10.                     $.each(data, function (key, item) {  
  11.                         // Add a list item for the product.  
  12.    
  13.                         $('  
  14.    
  15.    
  16. <li>', { text: ItemDetails(item) }).appendTo($('#books')).before("  
  17. ");  
  18.                         $("li").addClass("list-group-item list-group-item-info");  
  19.    
  20.                     });  
  21.                 });  
  22.         });  
  23.    
  24.         function ItemDetails(item) {  
  25.             return 'BookId : [ ' + item.id + ' ] -- Author Name : [ ' + item.author + ' ] -- Book Name : [ ' + item.bookName + ' ] -- Category : [ ' + item.category + ' ]';  
  26.         }  
  27.    
  28.         function find() {  
  29.             var id = $('#bookId').val();  
  30.             if (id == '') id = 0;  
  31.    
  32.             $.getJSON(uri + '/' + id)  
  33.                 .done(function (data) {  
  34.                     $('#library').text(ItemDetails(data));  
  35.                     $("p").addClass("list-group-item list-group-item-info");  
  36.                 })  
  37.                 .fail(function (jqXHR, textStatus, err) {  
  38.                     $('#library').text('Error: ' + err);  
  39.    
  40.                 });  
  41.         }  
Startup.cs
 
In the following code, we mention the "AddMvc()" in configuration service method. It will help to access the MVC related information at runtime. 
  1. using Microsoft.AspNetCore.Builder;  
  2. using Microsoft.AspNetCore.Hosting;  
  3. using Microsoft.Extensions.DependencyInjection;  
  4. using Microsoft.Extensions.Logging;  
  5.    
  6. namespace DotNetCoreExtentions  
  7. {  
  8.     public class Startup  
  9.     {  
  10.         // This method gets called by the runtime. Use this method to add services to the container.  
  11.         // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940  
  12.         public void ConfigureServices(IServiceCollection services)  
  13.         {  
  14.             services.AddMvc();  
  15.         }  
  16.    
  17.         // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.  
  18.         public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)  
  19.         {  
  20.             loggerFactory.AddConsole();  
  21.    
  22.             if (env.IsDevelopment())  
  23.             {  
  24.                 app.UseDeveloperExceptionPage();  
  25.             }  
  26.             app.UseFileServer();  
  27.             app.UseMvc();  
  28.         }  
  29.     }  
  30. }  
Output 1



JSON Output 1


Output 2
 

 
JSON Output 2

 
 
Reference
Conclusion
 
Thus, we learned how to create Rest API or Web API with ASP.NET Core 1.0 when starting from scratch. I hope you liked this article. Please share your valuable suggestions and feedback.