Share via


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

Introduction

There are several articles on the Google for creating Rest API or Web API with ASP.NET Core 1.0. In this article, We 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.

"Microsoft.AspNetCore.StaticFiles": "1.1.0",
"Microsoft.AspNetCore.Routing": "1.0.1",
"Microsoft.AspNetCore.Mvc.Core": "1.0.1",
"Microsoft.AspNetCore.Mvc.ViewFeatures": "1.0.1",
"Microsoft.AspNetCore.Mvc": "1.0.1"

Project.json

The following JSON file will show the full reference structure of our Web API application.

{  
  "dependencies": {  
    "Microsoft.NETCore.App": {  
      "version": "1.0.1",   
      "type": "platform" 
    },  
    "Microsoft.AspNetCore.Diagnostics": "1.0.0",   
    "Microsoft.AspNetCore.Server.IISIntegration": "1.0.0",   
    "Microsoft.AspNetCore.Server.Kestrel": "1.0.1",   
    "Microsoft.Extensions.Logging.Console": "1.0.0",   
    "Microsoft.AspNetCore.StaticFiles": "1.1.0",   
    "Microsoft.AspNetCore.Routing": "1.0.1",   
    "Microsoft.AspNetCore.Mvc.Core": "1.0.1",   
    "Microsoft.AspNetCore.Mvc.ViewFeatures": "1.0.1",   
    "Microsoft.AspNetCore.Mvc": "1.0.1" 
  },  
    
  "tools": {  
    "Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.0.0-preview2-final" 
  },  
    
  "frameworks": {  
    "netcoreapp1.0": {  
      "imports": [  
        "dotnet5.6",  
        "portable-net45+win8" 
      ]  
    }  
  },  
    
  "buildOptions": {  
    "emitEntryPoint": true,  
    "preserveCompilationContext": true 
  },  
    
  "runtimeOptions": {  
    "configProperties": {  
      "System.GC.Server": true 
    }  
  },  
    
  "publishOptions": {  
    "include": [  
      "wwwroot",  
      "web.config" 
    ]  
  },  
    
  "scripts": {  
    "postpublish": [ "dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" ]  
  }  
}

Project Structure

This is the project structure of our Rest API application.

LibraryDetails.cs

We have created the following class for property details in our Rest API application.

namespace DotNetCoreExtentions  
{  
    public class  LibraryDetails  
    {  
        public int  Id { get; set; }  
        public string  Author { get; set; }  
        public string  BookName { get; set; }  
        public string  Category { get; set; }  
            
    }  
}

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.

using System.Collections.Generic;  
using System.Linq;  
using Microsoft.AspNetCore.Mvc;  
using Microsoft.AspNetCore.Routing;  
    
// For more information on enabling Web API for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860 ; 
    
namespace DotNetCoreExtentions  
{  
    [Route("api/[controller]")]  
    public class  LibraryAPI : Controller  
    {  
        LibraryDetails[] LibraryDetails = new  LibraryDetails[]  
        {  
            new LibraryDetails { Id=1, BookName="Programming C# for Beginners", Author="Mahesh Chand", Category="C#" },  
            new LibraryDetails { Id=2, BookName="Setting Up SharePoint 2016 Multi-Server Farm In Azure", Author="Priyaranjan K S", Category="SharePoint"  },  
            new LibraryDetails { Id=3, BookName="SQL Queries For Beginners", Author="Syed Shanu", Category="Sql" },  
            new LibraryDetails { Id=4, BookName="OOPs Principle and Theory", Author="Syed Shanu", Category="Basic Concepts" },  
            new LibraryDetails { Id=5, BookName="ASP.NET GridView Control Pocket Guide", Author="Vincent Maverick Durano", Category="Asp.Net"  }  
        };  
            
        // GET: api/values  
        [HttpGet]  
        public IEnumerable<LibraryDetails> GetAllBooks()  
        {  
            return LibraryDetails;  
        }  
    
        // GET api/values/5  
        [HttpGet("{id}")]  
        public IActionResult Get(int id)  
        {  
            var books = LibraryDetails.FirstOrDefault((p) => p.Id == id);  
    
            var item = books;  
            if (item == null)  
            {  
                return NotFound();  
            }  
            return new  ObjectResult(item);  
        }  
            
        // POST api/values  
        [HttpPost]  
        public void  Post([FromBody]string value)  
        {  
        }  
    
        // PUT api/values/5  
        [HttpPut("{id}")]  
        public void  Put(int  id, [FromBody]string  value)  
        {  
        }  
    
        // DELETE api/values/5  
        [HttpDelete("{id}")]  
        public void  Delete(int  id)  
        {  
        }  
    }  
}

[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.

//api url  
        var uri = 'api/LibraryAPI';//[Route("api/[controller]")] instead of [controller] we can mention our API classname.  
    
        $(document).ready(function () {  
            // Send an AJAX request  
            $.getJSON(uri)  
                .done(function (data) {  
                    // On success, 'data' contains a list of products.  
    
                    $.each(data, function  (key, item) {  
                        // Add a list item for the product.  
    
                        $('  
    
    
<li>', { text: ItemDetails(item) }).appendTo($('#books')).before("  
");  
                        $("li").addClass("list-group-item list-group-item-info");  
    
                    });  
                });  
        });  
    
        function ItemDetails(item) {  
            return 'BookId : [ ' + item.id + ' ] -- Author Name : [ '  + item.author + ' ] -- Book Name : [ '  + item.bookName + ' ] -- Category : [ '  + item.category + ' ]';  
        }  
    
        function find() {  
            var id = $('#bookId').val();  
            if (id == '') id = 0;  
    
            $.getJSON(uri + '/' + id)   
                .done(function (data) {  
                    $('#library').text(ItemDetails(data));  
                    $("p").addClass("list-group-item list-group-item-info");  
                })  
                .fail(function (jqXHR, textStatus, err) {  
                    $('#library').text('Error: ' + err);  
    
                });  
        }

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.

using Microsoft.AspNetCore.Builder;  
using Microsoft.AspNetCore.Hosting;  
using Microsoft.Extensions.DependencyInjection;  
using Microsoft.Extensions.Logging;  
    
namespace DotNetCoreExtentions  
{  
    public class  Startup  
    {  
        // This method gets called by the runtime. Use this method to add services to the container.  
        // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940 ; 
        public void  ConfigureServices(IServiceCollection services)  
        {  
            services.AddMvc();  
        }  
    
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.  
        public void  Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)  
        {  
            loggerFactory.AddConsole();  
    
            if (env.IsDevelopment())  
            {  
                app.UseDeveloperExceptionPage();  
            }  
            app.UseFileServer();  
            app.UseMvc();  
        }  
    }  
}

Output 1

JSON Output 1

Output 2

JSON Output 2

See Also

It's recommended to read more articles related to ASP.NET Core.

Conclusion

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

Reference