Create (Use) Asp.Net Web API Service in Asp.Net MVC Application with Example

  Total Views : 5302
  Comments : 4
 
  Keywords : How to create web api in asp.net mvc with example, Step by step guide to create web api service in asp.net mvc, Create simple rest service using asp.net web api in mvc application

ASP.NET Web API is an ideal platform for building Restful applications on the .NET Platform. Using ASP.NET Web API it's easy to build HTTP service and reach a broad range of clients, including browsers and mobile, tablets, phablets all large and small devices. It's easy to create Web API as compare to that of WCF services.

 

In WCF services we have to configure binding to make it work where as in asp.net WEB API we don't require to do this. 

Why to use the Web API when there is web service?

Currently most mobile devices, browsers and tablets are the medium for accessing most of the internet and in this also people are using mobile apps most and to provide data to apps we are now going to use the Microsoft new technology called asp.net Web API.

 

Also one good thing in Web API is that when user sends request to web application for getting response in json format then we need to pass response headers as (contentType: 'application/json; charset=utf-8') and for getting XML as response we need to pass (contentType: 'application/xml; charset=utf-8') both response and request return by a single method. If we want to do same thing in web service then we need to create 2 different method for handling request one for sending response in JSON format and another one for getting response in XML and writing binding for these methods is a big Task.

 

Asp.net mvc reside in System.Web.Mvc namespace same like that web api resides in System.Web.Http namespace and asp.net mvc controller inherited from [Controller] and web api controller inherited from [ApiController]. In mvc we have action method which gets called from URL to handle request where as in Web API we have Http verbs method to handle request.

 

To understand in more detail let’s create a asp.net mvc web api application. In this application we will learn how to insert data in database using Web API and Rewrite data from database using web API display it on View using asp.net mvc. We are going to have a simple textbox for inserting comments and display it on page using asp.net web api in asp.net mvc application.

Create New Asp.Net MVC Application

Let's start with creating new asp.net mvc 4 application for that Open visual studio studio à Go to File à Select New à Select Project

 

create new asp.net mvc project from visual studio 2012

 

After that you will see new dialog will pop up for selecting your Template and Project type. From Templates select Visual C# à inside that select Web and then project type select ASP.NET MVC 4 Web Application and here we are giving name as “DemoWebAPI” then finally click on OK button

 

create asp.net mvc web application in asp.net web api example

 

After naming and click on OK button now new dialog will pop up for selecting template in that Select Web API template and set view engine as Razor and we are not going to create Unit testing for this project hence do not check this option and finally click OK like as shown below

 

select web api template in asp.net mvc web application

 

After selecting all options click on OK button our asp.net mvc project will create like as shown below

 

Asp.Net web api application in asp.net mvc

 

After creation of project we are going see normal folder structure which looks similar to MVC folder structure but if we want to see difference then just open folder controller it's having 2 controllers

 

      1) HomeController

      2) ValuesController

 

These two controllers are derived from different classes. HomeController is derived from controller and ValuesController is derived from ApiController.

 

HomeController will contain code like as shown below

 

public class HomeController : Controller

{

public ActionResult Index()

{

return View();

}

}

ValuesController will contain code like as shown below

 

public class ValuesController : ApiController

{

 

}

Now we will create new model in asp.net web api application. 

Adding New Model (Comment) in Asp.Net Web API

We are going to Add Model with Name Comment. In Solution Explorer, right click on Models folder Select Add à then select Class  à Name the class as Comment and finally click on Add button to create Model. 

 

Our new model (Comment) will contain code like as shown below.

 

using System;

using System.Collections.Generic;

using System.ComponentModel.DataAnnotations;

using System.Linq;

using System.Web;

namespace DemoWebAPI.Models

{

public class Comment

{

[Key]

public int CommentID { get; set; }

public string UserComment { get; set; }

public DateTime? Commentdate { get; set; }

}

}

After adding Comment Model now we will add folder with Name Repositories after that we are going to use Code First Approach for accessing database for that we are going to add class DbconnectionContext which will be inheriting from DbContext.

 

For Adding Folder Repositories first right click on DemoWebAPI then from list select Add à then Add New Folder and name it as Repositories.

 

Add new folder in asp.net web api application

 

After adding Repositories folder now we are going to add a class inside Repositories folder with Name DbconnectionContext like as shown below.

 

Add dbcontent class file in repositories folder in asp.net web api

 

After adding DbconnectionContext open class that will contain simple class with name DbconnectionContext now just Inherit from DbContext Class after this step in DbconnectionContext constructor we are going call base class (DbconnectionContext) and Provide connection string in it. After that just add a Dbset with name comment in DbconnectionContext class.

 

using DemoWebAPI.Models;

using System;

using System.Collections.Generic;

using System.Data.Entity;

using System.Linq;

using System.Web;

 

namespace DemoWebAPI.Repositories

{

public class DbconnectionContext : DbContext

{

public DbconnectionContext(): base("DefaultConnection")

{

}

public DbSet<Comment> Comment { get; set; }

}

}

After adding Repositories folder and DbconnectionContext class now we are going to add Interface in Repositories folder with Name IComments.cs

 

For adding interface in this folder right click on Repositories folder then from list select Add à then Add new item after selecting a new dialog of Add New Item will pop up from that Interface name it as IComments.cs and click on Add button.

 

Add new interface file in asp.net web api in asp.net mvc

 

After adding interface now let’s add a class with Name Comments in Repositories folder which will inherit Icomment Interface like as shown below.

 

Adding new comments class file in asp.net web api application

 

After adding class and interface now let’s declare method in Icomment Interface. We are going add 2 methods in this interface one for Inserting comments and other for displaying comments.

 

using DemoWebAPI.Models;

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

namespace DemoWebAPI.Repositories

{

interface IComments

{

void InsertComment(Comment Comment); //Inserting

IEnumerable<Comment> ListofComment(); //List of Comment

}

}

Now we will make comments class inheriting from IComments interface and implement it.

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using DemoWebAPI.Models;

namespace DemoWebAPI.Repositories

{

public class Comments : IComments

{

public void InsertComment(Comment Comment)

{

using (DbconnectionContext context = new DbconnectionContext())

{

context.Comment.Add(Comment);

context.SaveChanges();

}

}

public IEnumerable<Comment> ListofComment()

{

using (DbconnectionContext context = new DbconnectionContext())

{

var listofcomments = from comments in context.Comment

Select comments;

return listofcomments;

}

}

}

}

After adding & implementing class now let’s add connection to database. We are going to add connection string in Web.config because we need to tell it where to create Database.

 

<connectionStrings>

<add name="DefaultConnectionproviderName="System.Data.SqlClientconnectionString="Data Source=Sai-PC;

Database=AllCommentsDB; UID=sa; Password=Pass$123; App=EntityFramework" />

</connectionStrings>

After adding connection string to Web.config now let’s work with API Controller [ValuesController]. Open ValuesController class file and make following changes to method (Post and GetAlldata).

 

using DemoWebAPI.Models;

using DemoWebAPI.Repositories;

using System;

using System.Collections.Generic;

using System.Linq;

using System.Net;

using System.Net.Http;

using System.Web.Http;

 

namespace DemoWebAPI.Controllers

{

public class ValuesController : ApiController

{

IComments Icom;

public ValuesController()

{

Icom = new Comments();

}

// GET api/values

publicIEnumerable<Comment> GetAlldata()

{

return Icom.ListofComment();    

}

// GET api/values/5

public string Get(int id)

{

return"value";

}

// POST api/values

public void Post([FromBody]Comment Comment)

{

Icom.InsertComment(Comment); 

}

// PUT api/values/5

public void Put(int id, [FromBody]string value)

{

}

// DELETE api/values/5

public void Delete(int id)

{

}

}

}

Now we are going to work with * Real * Controller [HomeController]. Open HomeController and make following changes in it.

 

  1. We are going to add a Constructor with same name as class name [HomeController] inside that we are going to reference Interface to it inheriting class.
  2. Adding Action Method [InsertComment] will handle HTTP GET request.

Following is the code snippet of HomeController after making changes

 

using DemoWebAPI.Models;

using DemoWebAPI.Repositories;

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

 

namespace DemoWebAPI.Controllers

{

public class HomeController : Controller

{

IComments Icom;

public HomeController()

{

Icom = new Comments();

}

[HttpGet]

public ActionResult InsertComment()

{

return View(new Comment());

}

}

}

After making changes in controller let’s add view to all this stuff.

Adding New View in Asp.Net MVC

For adding view just right click inside controller action method (InsertComment) then select option Add View.

 

Adding view to controller by right click in asp.net mvc application

 

After selecting Add View option a New Wizard will pop up with Name (Add View). It will have view name same name as Action Method inside which we right click to add View. In this example we are going to create Strongly Typed view for that we check this option and in Model class we selected Comment model class.

 

adding view in asp.net mvc web api application

 

After selecting required option now finally click on Add button. A new view will be created inside Views folder and in that we will have folder with name of controller inside that our view will be placed and our view (InserComment) will contain code like as shown below.

 

@model DemoWebAPI.Models.Comment

@{

ViewBag.Title = "InsertComment";

}

<h2>InsertComment</h2>

@using (Html.BeginForm())

{

@Html.ValidationSummary(true)

<fieldset>

<legend>Comment</legend>

<div class="editor-label">

@Html.LabelFor(model => model.UserComment)

</div>

<div class="editor-field">

@Html.EditorFor(model => model.UserComment)

@Html.ValidationMessageFor(model => model.UserComment)

</div>

<p>

<input type="submit" value="Create"/>

</p>

</fieldset>

}

<div>

@Html.ActionLink("Back to List", "Index")

</div>

@section Scripts {

@Scripts.Render("~/bundles/jqueryval")

Now save application and RUN to access application URL will be like "http://localhost:####/home/InsertComment". 

 

Accessing view using asp.net web api in asp.net mvc application

 

After creating view let’s add Ajax to post data and getting data from API controller.

Calling ValuesController POST Method using jquery Ajax

First thing we need to add following scripts Referencein our applications.

 

<script src="~/Scripts/jquery-1.7.1.min.js"></script>

<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>

After adding scripts Reference we are going to write Function for inserting Data using Ajax. In this script we set Ajax Parameter which is required to post data.

 

var Comment = { "UserComment": $("#UserComment").val() };

 

type: "POST",

data: Comment,

url: '@Url.Action("Post", "api/values")',

success: function (data) {

GetData();

},

We are going to set Ajax first parameter type to “Post” because we are going to post data to APIController method and another parameter [ data: Comment ] for this parameter we are going to pass user entered comment.

 

After setting data parameter we need to define URL parameter of Ajax which will be ValuesController post method URL [api/values]. If we want to see how post method looks like then just open ValuesController in controller folder and find method name as Post. Final parameter is success in this we are not going to return any data we are calling another method to get data [GetData()]

 

Following is the script for inserting data using Ajax in asp.net mvc applications using web api.

 

<script type="text/javascript">

function PostData() {

debugger;

var Commenta = { "UserComment": $("#UserComment").val() };

$.ajax({

type: "POST",

data: Commenta,

url: '@Url.Action("Post", "api/values")',

success: function (data) {

GetData();

},

});

}

</script>

Following is the method we are calling for Inserting data.

 

// POST api/values

public void Post([FromBody]Comment Comment)

{

Icom.InsertComment(Comment);

}

After adding Inserting data function we need to show data which user have added for that we are going add another ajax method to get data [GetData()] and we are going to set parameter for getting data from Web API methods. In following script we set Ajax Parameter which is required to GET data.

 

type: "GET",

contentType: 'application/json; charset=utf-8',

url: 'http://localhost:1986/api/values',

dataType: "json",

success: function (data) {

$.each(data, function (i, mobj) {

$("#DivCom").append('<table class="table"><tr><td width="50px">' mobj.UserComment '</td></tr>

<div style="margin-top: 2px"></div>');

});

$("#DivCom").append('</table>');

}

We are going to set Ajax first parameter type to “GET” after that we are going to get data from APIController method for that we are going to set parameter [contentType: 'application/json; charset=utf-8'] after setting contentType. We need to define URL parameter of Ajax which will be from ValuesController GET method URL [api/values]. If we want to see how GET method looks like the just open ValuesController and find method name as GetAlldata

 

After setting URL we are going to set dataType in which format we want to receive data in case if we want in json format we need define like this [dataType: "json"]. Last parameter is success which is returning data we are going to get data in object. By using $.each object we are going to iterate it and show data in table format by appending data in table format.

 

<script type="text/javascript">

function GetData() {

$("#DivCom").empty();

$.ajax({

type: "GET",

contentType: 'application/json; charset=utf-8',

url: 'http://localhost:1986/api/values',

dataType: "json",

success: function (data) {

$.each(data, function (i, mobj) {

$("#DivCom").append('<table class="table"><tr><td width="50px">' mobj.UserComment '</td></tr>

<div style="margin-top: 2px"></div>');

});

$("#DivCom").append('</table>');

}

});

}

</script>

Our method for getting all data in controller will be like as shown below

 

// GET api/values

public IEnumerable<Comment> GetAlldata()

{

return Icom.ListofComment();

}

After creating method Now we are going to call this method on Click of Add Comment Button.

 

<inputtype="button"onclick="PostData();"value="Add Comment"/>

After completing all stuff we going to have a look on all controllers and views code snippets. Following are the complete code snippets of all controllers and views

Complete Code Snippet of ValuesController

Following is the complete code snippet of valuescontroller in asp.net mvc web api application.

 

using DemoWebAPI.Models;

using DemoWebAPI.Repositories;

using System;

using System.Collections.Generic;

using System.Linq;

using System.Net;

using System.Net.Http;

using System.Web.Http;

 

namespace DemoWebAPI.Controllers

{

public class ValuesController : ApiController

{

IComments Icom;

public ValuesController()

{

Icom = new Comments();

}

// GET api/values

public IEnumerable<Comment> GetAlldata()

{

return Icom.ListofComment();

}

// GET api/values/5

public string Get(int id)

{

return "value";

}

// POST api/values

public void Post([FromBody]Comment Comment)

{

Icom.InsertComment(Comment);

}

// PUT api/values/5

public void Put(int id, [FromBody]string value)

{

}

// DELETE api/values/5

public void Delete(int id)

{

}

}

}

Complete Code Snippet of HomeController

Following is the code complete code of HomeController in asp.net mvc web api application.

 

using DemoWebAPI.Models;

using DemoWebAPI.Repositories;

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

 

namespace DemoWebAPI.Controllers

{

public class HomeController : Controller

{

IComments Icom;

public HomeController()

{

Icom = new Comments();

}

[HttpGet]

public ActionResult InsertComment()

{

return View(new Comment());

}

}

}

Complete code of InsertComment View

Following is the code snippet of InsertComment view in asp.net mvc web api application.

 

@model DemoWebAPI.Models.Comment

 

@{

ViewBag.Title = "InsertComment";

Layout = null;

}

<style>

.table {

width: 70%;

max-width: 70%;

margin-bottom: 5px;

background-color:aliceblue;

}

</style>

<script src="~/Scripts/jquery-1.7.1.min.js"></script>

<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>

<script src="~/Scripts/jquery-1.9.1.min.js"></script>

<link href="~/bootstrap/css/bootstrap.min.css" rel="stylesheet"/>

<script src="~/bootstrap/js/bootstrap.min.js"></script>

<script type="text/javascript">

function PostData() {

var Commenta = { "UserComment": $("#UserComment").val() };

$.ajax({

type: "POST",

data: Commenta,

url: '@Url.Action("Post", "api/values")',

success: function (data) {

GetData();

},

});

}

</script>

<script type="text/javascript">

function GetData() {

$("#DivCom").empty();

$.ajax({

type: "GET",

contentType: 'application/json; charset=utf-8',

url: 'http://localhost:1034/api/values',

dataType: "json",

success: function (data) {

$.each(data, function (i, mobj) {

$("#DivCom").append('<table class="table"><tr><td width="50px">' mobj.UserComment '</td></tr><div style="margin-top: 2px"></div>');

});

$("#DivCom").append('</table>');

}

});

}

</script>

 

@using (Html.BeginForm())

{

@Html.ValidationSummary(true)

<div class="container">

<div style="margin-top: 5px"></div>

<div class="col-md-12">

@Html.LabelFor(model => model.UserComment)

</div>

<div style="margin-top: 5px"></div>

<div class="col-md-12">

@Html.TextBoxFor(model => model.UserComment, new { @class = "form-control" })

@Html.ValidationMessageFor(model => model.UserComment)

</div>

<div style="margin-top: 5px"></div>

<div class="col-md-12">

<input type="button" onclick="PostData();value="Add Comment"/>

</div>

<div style="margin-top: 10px"></div>

<div id="DivCom">

</div>

</div>

}

@section Scripts {

@Scripts.Render("~/bundles/jqueryval")

}

After completion of coding now save your application and run with url like "http://localhost:####/home/InsertComment".

 

After accessing page now enter comment in comment field and Click on Add Comment button the first going to get called is PostData function after that it is going to call GetData function result will be like as shown below.

 

output of create asp.net web api in asp.net mvc application

 

If you check output it looks little bit formatted because we added Bootstrap in design. To add Bootstrap to solution just download Bootstrap from link given below and add entire folder to your project "https://github.com/twbs/bootstrap/releases/download/v3.3.5/bootstrap-3.3.5-dist.zip". After adding just reference following files to view where you want to Use Bootstrap.

 

<link href="~/bootstrap/css/bootstrap.min.css" rel="stylesheet"/>

<script src="~/bootstrap/js/bootstrap.min.js"></script>

This is how we can create asp.net web api service and consume it in asp.net mvc application. 

 Comments (4)

  • Anne Yeiser tutlane registered profile image
     
    Anne Yeiser   Reply

    Cannot figure out how this works without db file

     Jan 30, 2016
    • Ajax tutlane registered profile image
       
      Ajax

      It is running because author selected code first approach.

       Apr 05, 2016
  • Razim Khan tutlane registered profile image
     
    Razim Khan   Reply

    great information thank you sir , c

     Jul 27, 2016
  • Rakesh Sharma tutlane registered profile image
     
    Rakesh Sharma   Reply

    Verry nice and easy tutorial

     Aug 31, 2016

Leave a comment

  • Default Tutlane User