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.
- "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.
Picture Source : https://rajeeshmenoth.wordpress.com
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;
-
-
-
- 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" }
- };
-
-
- [HttpGet]
- public IEnumerable<LibraryDetails> GetAllBooks()
- {
- return LibraryDetails;
- }
-
-
- [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);
- }
-
-
- [HttpPost]
- public void Post([FromBody]string value)
- {
- }
-
-
- [HttpPut("{id}")]
- public void Put(int id, [FromBody]string value)
- {
- }
-
-
- [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.
-
- var uri = 'api/LibraryAPI';
-
- $(document).ready(function () {
-
- $.getJSON(uri)
- .done(function (data) {
-
-
- $.each(data, function (key, item) {
-
-
- $('
-
-
- <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
- {
-
-
- public void ConfigureServices(IServiceCollection services)
- {
- services.AddMvc();
- }
-
-
- 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
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.