Welcome, Guest: Register On Nairaland / LOGIN! / Trending / Recent / New
Stats: 3,148,356 members, 7,800,717 topics. Date: Thursday, 18 April 2024 at 02:53 AM

How To Create Api In Asp.net Mvc 4 For Beginners - Programming - Nairaland

Nairaland Forum / Science/Technology / Programming / How To Create Api In Asp.net Mvc 4 For Beginners (1533 Views)

C# - Capturing File Name From A FileUpload Control In Asp.net / Fingerprint Programming In ASP.NET / Inserting And Retrieving Images To/From Database In ASP.NET (2) (3) (4)

(1) (Reply) (Go Down)

How To Create Api In Asp.net Mvc 4 For Beginners by mj(m): 11:20pm On Sep 18, 2013
The first part will be creating the Web API, second part will be Consuming it via Json, third part will be consuming the Web API as a web part in Microsoft Sharepoint Server.
Part One

ASP.NET Web API is a framework for building HTTP services that can be consume by a broad range of clients including browsers, mobiles, iphone and tablets. It is very similar to ASP.NET MVC since it contains the MVC features such as routing, controllers, action results, filter, model binders, IOC container or dependency injection. But it is not a part of the MVC Framework. It is a part of the core ASP.NET platform and can be used with MVC and other types of Web applications like Asp.Net WebForms. It can also be used as an stand-alone Web services application.

So, if you like to expose your service data to the browsers and as well as all these modern devices apps in fast and simple way, you should have an API which is compatible with browsers and all these devices.

In this tutorial, we will use ASP.NET Web API to create a web API that returns a list of Nairaland Moderators. The front-end web page uses jQuery to display the results.

Create a Web API Project
Start Visual Studio and select New Project from the Start page. Or, from the File menu, select New and then Project.
In the Templates pane, select Installed Templates and expand the Visual C# node. Under Visual C#, select Web. In the list of project templates, select ASP.NET MVC 4 Web Application. Name the project "NairalandAPI" and click OK.




In the New ASP.NET MVC 4 Project dialog, select Web API and click OK.


Adding a Model
A model is an object that represents the data in your application. ASP.NET Web API can automatically serialize your model to JSON, XML, or some other format, and then write the serialized data into the body of the HTTP response message. As long as a client can read the serialization format, it can deserialize the object. Most clients can parse either XML or JSON. Moreover, the client can indicate which format it wants by setting the Accept header in the HTTP request message.

Let's start by creating a simple model that represents a moderator.
If Solution Explorer is not already visible, click the View menu and select Solution Explorer. In Solution Explorer, right-click the Models folder. From the context menu, select Add then select Class.



Name the class "Moderator" and click on ADD.

Next, add the following properties to the Moderator class.

namespace NairalandAPI.Models
{
public class Moderator
{
public int Id { get; set; }
public string Name { get; set; }
public char Gender { get; set; }
public String SignupDate { get; set; }
public string Category { get; set; }
}
}

Adding a Controller
A controller is an object that handles HTTP requests. The New Project wizard created two controllers for you when it created the project. To see them, expand the Controllers folder in Solution Explorer.
• HomeController is a traditional ASP.NET MVC controller. It is responsible for serving HTML pages for the site, and is not directly related to Web API.
• ValuesController is an example WebAPI controller.

Go ahead and delete ValuesController, by right-clicking the file in Solution Explorer and selecting Delete.
Add a new controller, as follows:
In Solution Explorer, right-click the the Controllers folder. Select Add and then select Controller.



In the Add Controller wizard, name the controller "ModeratorsController". In the Template drop-down list, selectEmpty API Controller. Then click Add.



The Add Controller wizard will create a file named ModeratorsController.cs in the Controllers folder
If this file is not open already, double-click the file to open it. Replace the code in this file with the following:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using NairalandAPI.Models;
using System.Web.Http;
using System.Net;


namespace NairalandAPI.Controllers
{
public class ModeratorsController : ApiController
{
Moderator[] moderators = new Moderator[]
{
new Moderator { Id = 1, Name = "Javanian", Gender ='F', SignupDate = "April 09, 2012", Category = "Programming"},
new Moderator { Id = 2, Name = "Kodewriter", Gender ='M', SignupDate = "December 02, 2009", Category = "Programming"},
new Moderator { Id = 3, Name = "Fayimora", Gender ='M', SignupDate = "March 28, 2005", Category = "Programming"},
new Moderator { Id = 4, Name = "Slyr0x", Gender ='M', SignupDate = "June 24, 2010", Category = "Webmaster"},
new Moderator { Id = 5, Name = "MJ", Gender ='M', SignupDate = "February 28, 2006", Category = "Coming Soon"}

};

public IEnumerable<Moderator> GetAllModerators()
{
return moderators;
}

public Moderator GetModeratorById(int id)
{
var moderator = moderators.FirstOrDefault((p) => p.Id == id);
if (moderator == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
return moderator;
}

}
}

To keep this example simple, moderators are stored in a fixed array inside the controller class. Of course, in a real application, you would query a database or use some other external data source.

The controller defines two methods that return moderators:

The GetAllModerators method returns the entire list of moderatos as an IEnumerable<Moderator> type.
The GetModeratorById method looks up a single moderator by its ID.

That's it! You have a working web API. Each method on the controller maps to a URI.
Next post will be consuming the Web API.

2 Likes

Re: How To Create Api In Asp.net Mvc 4 For Beginners by talk2hb1(m): 12:31am On Sep 19, 2013
1^10000000 チャクラ流し for you!!!!!!!!!!!!
Re: How To Create Api In Asp.net Mvc 4 For Beginners by Nobody: 3:49am On Sep 20, 2013
Gosh i miss ASP.NET MVC i used 3 for a project it was quick to grasp esp LINQ WTF shocked
Re: How To Create Api In Asp.net Mvc 4 For Beginners by mj(m): 2:49pm On Sep 27, 2013
Part 2: Calling the Web API with Javascript and jQuery
Methods URI
GetAllModerators /api/moderators

GetModeratorById /api/moderators/id

A client can invoke the method by sending an HTTP GET request to the URI. Later, we'll look at how this mapping is done.So let's write a simple javascript client.
In Solution Explorer, expand the Views folder, and expand the Home folder under that. You should see a file named Index.cshtml. Double-click this file to open it.

Replace everything in this file with the following:

<div id="body">
<section class="content-wrapper main-content clear-fix">
<div>
<h2>All Nairaland Moderators</h2>


<table style="border: 1px #dedede solid;font-size: 11px; width: 400px;">
<thead style="background-color:green; border: 1px #dedede solid;font-size: 11px;color:#fff; font-weight:bold;">
<tr>
<td>ID</td> <td>Name</td> <td>Sex</td> <td>Category</td> <td>Signup Date</td>
</tr>
</thead>
<tbody>

</tbody>
</table>
</div>
<div>
<h2>Search by Moderator ID</h2>
<input type="text" id="modId" size="5" />
<input type="button" value="Search" onclick="find();" />
<p id="moderator" />
</div>
</section>
</div>

@section scripts {
<script>
var apiUrl = 'api/moderators';

$(document).ready(function () {
// Sending an AJAX request
$.getJSON(apiUrl)
.done(function (data) {
$.each(data, function (key, item) {
var tr;
tr = $('<tr/>');
tr.append("<td>" + item.Id + "</td>"wink;
tr.append("<td>" + item.Name + "</td>"wink;
tr.append("<td>" + item.Gender + "</td>"wink;
tr.append("<td>" + item.Category + "</td>"wink;
tr.append("<td>" + item.SignupDate + "</td>"wink;
$('table').append(tr);

});
});
});

function formatItem(item) {
return 'Name: ' + item.Name;
}

function find() {
var id = $('#modId').val();
$.getJSON(apiUrl + '/' + id)
.done(function (data) {
$('#moderator').text(formatItem(data));
})
.fail(function (jqXHR, textStatus, err) {
$('#moderator').text('Error: ' + err);
});
}
</script>
}
Getting a List of Moderators
To get a list of moderators, send an HTTP GET request to "/api/moderators".
The jQuery getJSON function sends an AJAX request. For response contains array of JSON objects. The done function specifies a callback that is called if the request succeeds. In the callback, we update the DOM with the moderator information.

$(document).ready(function () {
// Sending an AJAX request
$.getJSON(apiUrl)
.done(function (data) {
$.each(data, function (key, item) {
var tr;
tr = $('<tr/>');
tr.append("<td>" + item.Id + "</td>"wink;
tr.append("<td>" + item.Name + "</td>"wink;
tr.append("<td>" + item.Gender + "</td>"wink;
tr.append("<td>" + item.Category + "</td>"wink;
tr.append("<td>" + item.SignupDate + "</td>"wink;
$('table').append(tr);

});
});
});

Getting a Moderator By ID
To get a moderator by ID, send an HTTP GET request to "/api/moderator/id", where id is the moderator ID.

function find() {
var id = $('#modId').val();
$.getJSON(apiUrl + '/' + id)
.done(function (data) {
$('#moderator').text(formatItem(data));
})
.fail(function (jqXHR, textStatus, err) {
$('#moderator').text('Error: ' + err);
});
}
We still call getJSON to send the AJAX request, but this time we put the ID in the request URI. The response from this request is a JSON representation of a single product.

Running the Application
Press F5 to start debugging the application. The web page should look like the following:

It might not the best in web design, but it shows that our HTTP service is working. You can get a moderator by ID by entering the ID in the text box:


Congratulations, we now have a working web service.

(1) (Reply)

Help Him Create Interdependent Fields Microsoft Access / The Best Platform For The Fastest PHP Engine / Team Members Needed!!!

(Go Up)

Sections: politics (1) business autos (1) jobs (1) career education (1) romance computers phones travel sports fashion health
religion celebs tv-movies music-radio literature webmasters programming techmarket

Links: (1) (2) (3) (4) (5) (6) (7) (8) (9) (10)

Nairaland - Copyright © 2005 - 2024 Oluwaseun Osewa. All rights reserved. See How To Advertise. 36
Disclaimer: Every Nairaland member is solely responsible for anything that he/she posts or uploads on Nairaland.