Objectives
- We Will Create An ASP.NET WEB API.
- We Will Use SQL Server Database For Data Access.
- We Will Use Database First Approach Of Entity Framework In This Web API.
- After Creating An API, We Are Going To Check That Web API is Working Correctly Or Not.
- After That We Will Consume The Web API In ASP.NET MVC Application
Scenario – ASP.NET WEB API With SQL Server Database

What is OK() Method in ASP.NET Web API ?
- Web API writes the serialized value into the response body. The response status code is 200 (OK).
- A disadvantage of this approach is that you cannot directly return an error code, such as 404. However, you can throw an HttpResponseException for error codes.
HTTP Verbs In ASP.NET Web API
RESOURCE | VERB / REQUEST | RESULT |
---|---|---|
/Students | GET | Gets list of students |
/Students/1 | GET | Gets student with id = 1 |
/Students | POST | Creates a new student |
/Students/1 | PUT | Updates student with id = 1 |
/Students/1 | DELETE | Deletes student with id = 1 |
What Is Postman Tool ?
- The Postman is very useful application API Testing.
- The Postman is a HTTP Client that is used to tests HTTP requests.
- We can utilize APIs in our GUI (graphical User Interface).
- By using Postman we can obtain different types of responses comes from Web API.
- It is very useful to validate the results of Web API.
- Postman’s features simplify each step of building an API.
- By using Postman you can create better APIs and test it faster.
- The Postman tool allows you to design, test, debug, automated testing, document, monitor and publish the APIs.
- Postman is also called API Development Platform.
- Download Postman Tool from this link https://www.postman.com
Consuming ASP.NET WEB API In ASP.NET MVC APP

What Is HttpClient In ASP.NET Web API ?
- An HttpClient can be used to send requests and retrieve their responses.
- An HttpClient provides configuration information, and resource sharing, for all requests sent through it.
NewApiController Source Code
using MyNewAspWebAPI.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Mvc;
namespace MyNewAspWebAPI.Controllers
{
public class NewApiController : ApiController
{
practiceEntities db = new practiceEntities();
[System.Web.Http.HttpGet]
public IHttpActionResult Index()
{
List<student> obj = db.students.ToList();
return Ok(obj);
}
[System.Web.Http.HttpGet]
public IHttpActionResult Index(int id)
{
var obj = db.students.Where(model => model.std_id == id).FirstOrDefault();
return Ok(obj);
}
}
}
ConsumeController Source Code
using MyNewAspWebAPI.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web;
using System.Web.Mvc;
namespace MyNewAspWebAPI.Controllers
{
public class ConsumeController : Controller
{
// GET: Consume
HttpClient client = new HttpClient();
public ActionResult Index()
{
List<student> list = new List<student>();
client.BaseAddress = new Uri("http://localhost:1808/api/NewApi");
var response = client.GetAsync("NewApi");
response.Wait();
var test = response.Result;
if(test.IsSuccessStatusCode)
{
var display = test.Content.ReadAsAsync<List<student>>();
display.Wait();
list = display.Result;
}
return View(list);
}
}
}
Index.cshtml Source Code
@model IEnumerable<MyNewAspWebAPI.Models.student>
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.std_name)
</th>
<th>
@Html.DisplayNameFor(model => model.std_gender)
</th>
<th>
@Html.DisplayNameFor(model => model.std_age)
</th>
<th>
@Html.DisplayNameFor(model => model.std_class)
</th>
<th>
@Html.DisplayNameFor(model => model.t_id)
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.std_name)
</td>
<td>
@Html.DisplayFor(modelItem => item.std_gender)
</td>
<td>
@Html.DisplayFor(modelItem => item.std_age)
</td>
<td>
@Html.DisplayFor(modelItem => item.std_class)
</td>
<td>
@Html.DisplayFor(modelItem => item.t_id)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id=item.std_id }) |
@Html.ActionLink("Details", "Details", new { id=item.std_id }) |
@Html.ActionLink("Delete", "Delete", new { id=item.std_id })
</td>
</tr>
}
</table>
practiceEntities Database Context Class Code
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace MyNewAspWebAPI.Models
{
using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
public partial class practiceEntities : DbContext
{
public practiceEntities()
: base("name=practiceEntities")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public virtual DbSet<student> students { get; set; }
}
}
Student Model Class Code
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace MyNewAspWebAPI.Models
{
using System;
using System.Collections.Generic;
public partial class student
{
public int std_id { get; set; }
public string std_name { get; set; }
public string std_gender { get; set; }
public Nullable<int> std_age { get; set; }
public Nullable<int> std_class { get; set; }
public Nullable<int> t_id { get; set; }
}
}
WebApiConfig.cs Source Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
namespace MyNewAspWebAPI
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
}
RouteConfig.cs Source Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace MyNewAspWebAPI
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Consume", action = "Index", id = UrlParameter.Optional }
);
}
}
}
Click Below Link to Download Source Code Of This Blog
https://www.mediafire.com/file/v6kyqwxc3gxk8wy/MyNewAspWebAPI.rar/file
Click Below Link to Download Notes Of This Blog
https://www.mediafire.com/file/r32swvw61edzx17/Creating+Web+API+with+SQL+Database.pptx/file
https://www.mediafire.com/file/z5ns2r75otzkei6/What+Is+PostMan+Tool.pptx/file
https://www.mediafire.com/file/0u26ta4dtuatjid/Consuming+ASP.NET+WEB+API.pptx/file
No responses yet