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.
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.
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"
"Microsoft.AspNetCore.Mvc.ViewFeatures"
"Microsoft.AspNetCore.Mvc"
The following JSON file will show the full reference structure of our Web API application.
{
"dependencies"
: {
"Microsoft.NETCore.App"
"version"
"type"
"platform"
},
"Microsoft.AspNetCore.Diagnostics"
"1.0.0"
"Microsoft.AspNetCore.Server.IISIntegration"
"Microsoft.AspNetCore.Server.Kestrel"
"Microsoft.Extensions.Logging.Console"
"tools"
"Microsoft.AspNetCore.Server.IISIntegration.Tools"
"1.0.0-preview2-final"
"frameworks"
"netcoreapp1.0"
"imports"
: [
"dotnet5.6"
"portable-net45+win8"
]
}
"buildOptions"
"emitEntryPoint"
true
"preserveCompilationContext"
"runtimeOptions"
"configProperties"
"System.GC.Server"
"publishOptions"
"include"
"wwwroot"
"web.config"
"scripts"
"postpublish"
"dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%"
This is the project structure of our Rest API application.
We have created the following class for property details in our Rest API application.
namespace
DotNetCoreExtentions
public
class
LibraryDetails
int
Id {
get
;
set
; }
string
Author {
BookName {
Category {
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".
The following code contains the CRUD operation of REST API application.
using
System.Collections.Generic;
System.Linq;
Microsoft.AspNetCore.Mvc;
Microsoft.AspNetCore.Routing;
// For more information on enabling Web API for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860 ;
[Route(
"api/[controller]"
)]
LibraryAPI : Controller
LibraryDetails[] LibraryDetails =
new
LibraryDetails[]
LibraryDetails { Id=1, BookName=
"Programming C# for Beginners"
, Author=
"Mahesh Chand"
, Category=
"C#"
LibraryDetails { Id=2, BookName=
"Setting Up SharePoint 2016 Multi-Server Farm In Azure"
"Priyaranjan K S"
"SharePoint"
LibraryDetails { Id=3, BookName=
"SQL Queries For Beginners"
"Syed Shanu"
"Sql"
LibraryDetails { Id=4, BookName=
"OOPs Principle and Theory"
"Basic Concepts"
LibraryDetails { Id=5, BookName=
"ASP.NET GridView Control Pocket Guide"
"Vincent Maverick Durano"
"Asp.Net"
};
// GET: api/values
[HttpGet]
IEnumerable<LibraryDetails> GetAllBooks()
return
LibraryDetails;
// GET api/values/5
[HttpGet(
"{id}"
IActionResult Get(
id)
var books = LibraryDetails.FirstOrDefault((p) => p.Id == id);
var item = books;
if
(item ==
null
)
NotFound();
ObjectResult(item);
// POST api/values
[HttpPost]
void
Post([FromBody]
value)
// PUT api/values/5
[HttpPut(
Put(
id, [FromBody]
// DELETE api/values/5
[HttpDelete(
Delete(
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".
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(
(data) {
// On success, 'data' contains a list of products.
$.each(data,
(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"
);
});
ItemDetails(item) {
'BookId : [ '
+ item.id +
' ] -- Author Name : [ '
+ item.author +
' ] -- Book Name : [ '
+ item.bookName +
' ] -- Category : [ '
+ item.category +
' ]'
find() {
id = $(
'#bookId'
).val();
(id ==
''
) id = 0;
$.getJSON(uri +
'/'
+ id)
'#library'
).text(ItemDetails(data));
"p"
})
.fail(
(jqXHR, textStatus, err) {
).text(
'Error: '
+ err);
In the following code, we mention the "AddMvc()" in configuration service method. It will help to access the MVC related information at runtime.
Microsoft.AspNetCore.Builder;
Microsoft.AspNetCore.Hosting;
Microsoft.Extensions.DependencyInjection;
Microsoft.Extensions.Logging;
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 ;
ConfigureServices(IServiceCollection services)
services.AddMvc();
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
loggerFactory.AddConsole();
(env.IsDevelopment())
app.UseDeveloperExceptionPage();
app.UseFileServer();
app.UseMvc();
It's recommended to read more articles related to ASP.NET Core.
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.