Skip to main content

Create Web API in Asp.Net Core MVC with Example

Introduction:

Here we will learn how to create web api in asp.net core mvc with example or asp.net core mvc rest web api tutorial with example or asp.net core mvc restful api with example or implement web api usingasp.net core with examples. By using asp.net core mvc web api templates we can easily implement restful web api services based on our requirements.

To create web api first we need to create new project for that Open visual studio Ã  Go to File menu Ã select New Ã  Project like as shown below


 Now from web templates select Asp.Net Core Web Application (.NET Core) and give name (CoreWebAPI) to the project and click OK button like as shown below.

Once we click OK button new template will open in that select Web API from Asp.Net Core templates like as shown below

Our asp.net core web api project structure will be like as shown below

Now add new “Models” folder in project by right click on project select Add Ã  New Folder like as shown below

Now add new class “UserDetails” in Models folder and write the code like as shown below


namespace CoreWebAPI.Models
{
public class UserDetails
{
public int userid { getset; }
public string username { getset; }
public string education { getset; }
public string location { getset; }
}
}

In .net core we need to add repository class files in our project to maintain our application logic and interface layer to achieve dependency injection. For that right click on your Models folder and add new class file and give name as “IUserRepository” and writhe code like as shown below

IUserRepository.cs


using System.Collections.Generic;

namespace CoreWebAPI.Models
{
public interface IUserRepository
{
List<UserDetails> AddUser(UserDetails user);
IEnumerable<UserDetails> GetUsers();
UserDetails FindUser(int userid);
}
}

We are done with interface layer now we need to create application logic file for that right click onModels folder Ã  add new class file Ã  give name as “UserRepository” and write the code like as shown below (Here we are inheriting properties from IUserRepository interface file).

UserRepository.cs


using System.Collections.Generic;

namespace CoreWebAPI.Models
{
public class UserRepository:IUserRepository
{
List<UserDetails> _userinfo = new List<UserDetails>();
public UserRepository()
{
AddUser(new UserDetails { userid=1,username="Suresh Dasari",education="B.Tech",location="Chennai" });
}
public List<UserDetails> AddUser(UserDetails user)
{
_userinfo.Add(user);
return _userinfo;
}
public IEnumerable<UserDetails> GetUsers()
{
return _userinfo;
}
public UserDetails FindUser(int userid)
{
return _userinfo.Find(x => x.userid == userid);
}
}
}
Now we need to register our repository application logic file and interface layers with dependency injection container for that open Startup.cs file and add following namespace to access Models folder references


using CoreWebAPI.Models;

In ConfigureServices method of Startup.cs file add the highlighted code like as shown below

Startup.cs


public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc();
services.AddSingleton<IUserRepositoryUserRepository>();
}

Now we will add new controller to write our custom methods for that right click on Controllers folder and select Add Ã  New Item Ã  In new items select Web API Controller class template and give name as “UserController” like as shown below.

Now open UserController file and write the code like as shown below

UserController.cs


using System;
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using CoreWebAPI.Models;

namespace CoreWebAPI.Controllers
{
[Route("api/[controller]")]
public class UserController : Controller
{
public new IUserRepository User { getset; }
public UserController(IUserRepository _user)
{
User = _user;
}
// GET: api/values
[HttpGet]
public IEnumerable<UserDetails> GetAllUsers()
{
return User.GetUsers();
}
// GET api/values/5
[HttpGet("{userid}")]
public IActionResult GetUserById(string userid)
{
if(!string.IsNullOrEmpty(userid))
{
var result = User.FindUser(Convert.ToInt32(userid));
if (result == null)
return NoContent();
else
return new ObjectResult(result);
}
else
{
return BadRequest();
}
}

// POST api/values
[HttpPost]
public IActionResult insertuserdetails([FromBody]UserDetails userinfo)
{
if (userinfo == null)
return BadRequest();
else
{
var results= User.AddUser(userinfo);
return new OkObjectResult(results);
}
}
}
}


We can access above controller methods using the URL’s like as shown below.

GET Requests

/api/user – Get all the users
/api/user/{userid} – Get user details based on userid

Post Request

/api/user – It insert user details.
Now we will test our controller methods with using postman or fiddler.

Get all users (/api/user)

Get User Details based on userid (/api/user/1)

Insert and Show User Details (/api/user)

Comments

Popular posts from this blog

Scenario : Cloud Computing

ASP.NET Core - MVC Setup

Here we will set up the MVC framework in our FirstAppDemo application. We will proceed by building a web application on top of the ASP.NET Core, and more specifically, the ASP.NET Core MVC framework. We can technically build an entire application using only middleware, but ASP.NET Core MVC gives us the features that we can use to easily create HTML pages and HTTP-based APIs. To setup MVC framework in our empty project, follow these steps − Install the  Microsoft.AspNet.Mvc  package, which gives us access to the assemblies and classes provided by the framework. Once the package is installed, we need to register all of the services that ASP.NET MVC requires at runtime. We will do this inside the  ConfigureServices  method. Finally, we need to add middleware for ASP.NET MVC to receive requests. Essentially this piece of middleware takes an HTTP request and tries to direct that request to a C# class that we will write. Step 1  − Let us go to the NuGet package manager by ri

SQL Server Tutorial - Date functions

1. Get month names with month numbers: In this query we will learn about  How to get all month names with month number in SQL Server . I have used this query to bind my dropdownlist with month name and month number. 1 2 3 4 5 6 7 8 9 10 11 12 ;WITH months(MonthNumber) AS (      SELECT 0      UNION ALL      SELECT MonthNumber+1      FROM months      WHERE MonthNumber < 12 ) SELECT DATENAME(MONTH,DATEADD(MONTH,-MonthNumber,GETDATE())) AS [MonthName],Datepart(MONTH,DATEADD(MONTH,-MonthNumber,GETDATE())) AS MonthNumber FROM months ORDER BY Datepart(MONTH,DATEADD(MONTH,-MonthNumber,GETDATE())) ; 2. Get name of current month: In this query we will learn about  How to get name of current month in SQL Server . 1 select DATENAME(MONTH, GETDATE()) AS CurrentMonth 3. Get name of day: In this query we will learn about  How to get name of day in SQL Server . 1 select DATENAME(WEEKDAY, GETDATE()) AS TodayI