Updated March 15, 2023
Introduction to ASP.NET MVC Web API
ASP.NET MVC Web API is an ideal platform for creating the RESTful Application; while creating APIs on the Web, there will be various methods to create API on Web. ASP.NET Web API is the Framework that is simple to build HTTP Service that reaches a broad range of clients, which includes mobile devices, browsers, and so on. In addition, it supports for Self-Hosting or IIS Hosting.
What is ASP.NET MVC Web API?
ASP.NET Web API is the Framework for building the HTTP Service, which reaches a broad range of clients, including browsers, mobile devices, etc. Creating the ASP.NET Web API is simple when compared to WCF Services. ASP.NET Web API is the superior platform for creating RESTful applications.
Uses of Web API
- NET Web API supports CRUD actions that work with HTTP verbs like GET, POST, DELETE, and PUT.
- The responses of Web API have an Accept header and HTTP Status code.
- Web API supports non-SOAP services like various text formats like XML and JSON or can use Custom MediaTypeFormatter.
- Web API accepts and builds content that is not object-oriented, like images, PDF contents, etc.
- It supports for Self-Hosting or IIS Hosting.
- Web API supports MVC features like Controller, Action Results, Routing, Dependency Injection, Filters, IOC Container, or Mobile Binders.
- Supports OData by including new[Queryable] attribute on Controller method it returns IQueryable and customer used the method for OData Query Composition.
Create ASP.NET MVC Web API
Let’s see the creation of a new ASP.NET MVC Application, Open Visual Studio,
File -> New -> Project
Select the Template, project type, and the ASP.NET MVC 4 Web Application from the new dialog. Next, give the appropriate name to the project and select Ok.
Once given a proper name, select the Web API template and view the engine as Razor. Finally, click ok.
Once doing all processes, click OK, and the project structure will look as shown below,
After creating the project, we will see a normal folder structure similar to the MVC one. But, first, open the folder controller if we want to see a difference. It has two controllers.
The folder structure is similar to the MVC Folders Structure; to see the difference, click on Controller; there will be two Controllers; they are
- HomeController – it is derived from the Controller
- ValuesController – it is derived from ApiController
To include New Model in ASP.NET Web API
Let’s consider the new Model Name as Comment; in the Solution Explorer, just by right-clicking on Models Folder and Addà New Classà, name it as Comment and finally click Add to create a new model.
Comment Class
public class Comment
{
[Key]
public int CommentID { get; set; }
public string UserComment { get; set; }
public DateTime? Commentdate { get; set; }
}
Once including the Comment model, add the Folder Repositories; here in this application, we are using the Code-First Approach to access the database, then to include the class DbConnectiuonContext inherited from DbContext as shown below,
Once including the DbconnectionContext Class, look at the class containing the code below shown,
public class DbconnectionContext : DbContext
{
public DbconnectionContext()
: base("DefaultConnection")
{
}
public DbSet<Comment> Comment { get; set; }
}
To add the connection string in Web. Config to mentioning like where the database is created,
<connectionStrings>
<add name=" " providerName="System.Data.SqlClient" connectionString=" " />
</connectionStrings>
After adding the Repositories folder and DbconnectionContext class, we will add Interface in the Repositories folder with Name IComments.cs.
After adding class and interface, let’s declare a method in Icomment Interface. We will add two methods to this interface, one for Inserting comments and the others for displaying comments.
Once including the DbconnectionContext class and Repositories Folder, we added the interface in Repositories Folder with the name IComments.cs.
interface IComments
{
void InsertComment(Comment Comment); // to insert the data
IEnumerable<Comment> ListofComment(); // to display the List of Comment
}
The repositories Folder looks as
Now we will make a comments class inheriting from the IComments interface and implement it.
To make Comment Class inheriting from IComments Interface and implement as
public class Comments : IComments
{
public void InsertComment(Comment Comment)
{
using (DbconnectionContext db_context = new DbconnectionContext())
{
db_context.Comment.Add(Comment);
db_context.SaveChanges();
}
}
public IEnumerable<Comment> ListofComment()
{
using (DbconnectionContext db_context = new DbconnectionContext())
{
var _list = from comments in db_context.Comment
Select comments;
return _list;
}
}
}
Let’s start the code with API Controller [ValuesController]. Open the ValuesControllers and code with the following methods like Post and GetAllData
public class ValuesController : ApiController
{
IComments CommentObj;
public ValuesController()
{
CommentObj = new Comments();
}
// GET api/values
publicIEnumerable<Comment> GetAlldata()
{
return CommentObj.ListofComment();
}
// GET api/values/5
public string Get(int id)
{
return "value";
}
// POST api/values
public void Post([FromBody]Comment Comment)
{
CommentObj.InsertComment(Comment);
}
// PUT api/values/5
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/values/5
public void Delete(int id)
{
}
}
In the HomeController, we add the Constructors with the same name as the class name [HomeController]; inside that, we use the Interface to inherit the class. The Action Method (InsertComment) handles the HTTP GET request. Let’s see the HomeController coding given below,
public class HomeController : Controller
{
IComments CommentObj;
public HomeController()
{
CommentObj = new Comments();
}
[HttpGet]
public ActionResult InsertComment()
{
return View(new Comment());
}
}
The View part of InsertComment in ASP.NET MVC Web API Application code below,
@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")
}
Finally, save the application and execute the application with the URL like
“http://localhost:____/home/InsertComment”
Conclusion
This article has explained the features of Web API and their usage and seen the creation of ASP.NET Web API Service and how to consume it in ASP.NET MVC Application. Hope the article helps to understand.
Recommended Articles
We hope that this EDUCBA information on “ASP.NET MVC Web API” was beneficial to you. You can view EDUCBA’s recommended articles for more information.