In this blog, we will perform Web API CRUD operations using Entity Framework and ASP.Net MVC.
What is ASP.Net Web API?
Web API is the Microsoft open source technology for developing REST services based on HTTP protocol. ASP.Net Web API is a framework for building, consuming HTTP based services. The advantage of Web API is that it can be consumed by a wide range of clients like a web browser and mobile applications.
What is Entity Framework?
Entity Framework is an object-relational mapping that allows developers to work with relational databases. Entity Framework is an open-source framework. Read More…
You may read more on MVC, Web API and Angular |
Follow the below steps to create a Web API project in Visual Studio 2017
Let’s open the Visual Studio 2017 and start the demonstration.
First, create a Web API project in Visual Studio 2017.
Add ADO.Net Entity Data Model to this project.
To do this follow the below steps.
Select Approach.
Set the connection string.
Select the Entity Framework version.
Select a database object you want to use.
I am selecting ProductMaster table as I will demonstrate CRUD operation for the Product Table.
Create Web API 2 Project
Select Model Class from dropdown and Data Context class as shown below.
WebAPI2 controller code will look like this.
namespace WebAPI2Demo.Controllers { public class ProductMastersController : ApiController { private ReviewAndShareEntities db = new ReviewAndShareEntities(); // GET: api/ProductMasters public IQueryable<ProductMaster> GetProductMasters() { return db.ProductMasters; } // GET: api/ProductMasters/5 [ResponseType(typeof(ProductMaster))] public IHttpActionResult GetProductMaster(int id) { ProductMaster productMaster = db.ProductMasters.Find(id); if (productMaster == null) { return NotFound(); } return Ok(productMaster); } // PUT: api/ProductMasters/5 [ResponseType(typeof(void))] public IHttpActionResult PutProductMaster(int id, ProductMaster productMaster) { if (!ModelState.IsValid) { return BadRequest(ModelState); } if (id != productMaster.id) { return BadRequest(); } db.Entry(productMaster).State = EntityState.Modified; try { db.SaveChanges(); } catch (DbUpdateConcurrencyException) { if (!ProductMasterExists(id)) { return NotFound(); } else { throw; } } return StatusCode(HttpStatusCode.NoContent); } // POST: api/ProductMasters [ResponseType(typeof(ProductMaster))] public IHttpActionResult PostProductMaster(ProductMaster productMaster) { if (!ModelState.IsValid) { return BadRequest(ModelState); } db.ProductMasters.Add(productMaster); db.SaveChanges(); return CreatedAtRoute(“DefaultApi”, new { id = productMaster.id }, productMaster); } // DELETE: api/ProductMasters/5 [ResponseType(typeof(ProductMaster))] public IHttpActionResult DeleteProductMaster(int id) { ProductMaster productMaster = db.ProductMasters.Find(id); if (productMaster == null) { return NotFound(); } db.ProductMasters.Remove(productMaster); db.SaveChanges(); return Ok(productMaster); } protected override void Dispose(bool disposing) { if (disposing) { db.Dispose(); } base.Dispose(disposing); } private bool ProductMasterExists(int id) { return db.ProductMasters.Count(e => e.id == id) > 0; } } } |
Host your web API in IIS and test.
Open IIS and Add Website…
Access the URL, you will see the result in XML format as shown below.
To get a particular record, use below URL.
/api/ProductMastsers/<id>
Select MVC from Project template.
ProductModel class.
public class ProductModel { public int id { get; set; } public string product { get; set; } public decimal cost { get; set; } public int stock { get; set; } } |
Index View to show Product List.
@model IEnumerable<WebAPI2Consumer.Models.ProductModel> @{ ViewBag.Title = “Index”; } <h2>Index</h2> <p> @Html.ActionLink(“Create New”, “Create”) </p> <table class=”table”> <tr> <th> @Html.DisplayNameFor(model => model.product) </th> <th> @Html.DisplayNameFor(model => model.cost) </th> <th> @Html.DisplayNameFor(model => model.stock) </th> <th></th> </tr> @foreach (var item in Model) { <tr> <td> @Html.DisplayFor(modelItem => item.product) </td> <td> @Html.DisplayFor(modelItem => item.cost) </td> <td> @Html.DisplayFor(modelItem => item.stock) </td> <td> @Html.ActionLink(“Edit”, “Edit”, new { id=item.id }) | @Html.ActionLink(“Details”, “Details”, new { id=item.id }) | @Html.ActionLink(“Delete”, “Delete”, new { id=item.id }) </td> </tr> } </table> |
In order to create a Web API client.
Add Microsoft.AspNet.Webapi.Client using NuGet package manager.
Host your MVC project in IIS.
Open IIS and Add a new website.
If you don’t want to host your application and web API in IIS.
Right-click on Solution name in visual studio 2017 solution explorer and select properties.
Set Multiple startup projects for Web API and MVC project i.e. Web API consumer.
public class ProductController : Controller { public static HttpClient webClient = new HttpClient(); // GET: Product public ActionResult Index() { IEnumerable<ProductModel> products; HttpResponseMessage webResponse = webClient.GetAsync(“http://localhost:90/api/ProductMasters”).Result; products = webResponse.Content.ReadAsAsync<IEnumerable<ProductModel>>().Result; return View(products); } } |
Now click on Create New link on the Product list view Page.
public ActionResult Create() { return View(); } [HttpPost] public ActionResult Create(ProductModel productModel) { HttpResponseMessage httpResponseMessage = webClient.PostAsJsonAsync(“http://localhost:90/api/ProductMasters”, productModel).Result; return View(); } |
public ActionResult Edit() { return View(); } [HttpPost] public ActionResult Edit(ProductModel productModel) { HttpResponseMessage httpResponseMessage = webClient.PutAsJsonAsync(“http://localhost:90/api/ProductMasters/” + productModel.id, productModel).Result; return View(); } |
public ActionResult Delete(int id) { HttpResponseMessage httpResponseMessage = webClient.DeleteAsync(“http://localhost:90/api/ProductMasters/” + id).Result; return View(); } |
@model WebAPI2Consumer.Models.ProductModel @{ ViewBag.Title = “Delete”; } <h2>Delete</h2> <div> <h4>ProductModel</h4> <hr /> <h2>Record Deleted Successfully</h2> @using (Html.BeginForm()) { @Html.AntiForgeryToken() <div class=”form-actions no-color”> @Html.ActionLink(“Back to List”, “Index”) </div> } </div> |
To view the details of a particular record, we need a separate action.
public ActionResult Details(int id) { HttpResponseMessage httpResponse = webClient.GetAsync(“http://localhost:90/api/ProductMasters/” + id).Result; return View(httpResponse.Content.ReadAsAsync<ProductModel>().Result); } |
Click on the Details link, you will see the details of that record.