In this article, we will see how to create Web API, hosting of Web API and how to use Web API in an application.
ASP.NET Web API is a framework that makes it easy to build HTTP services which can be easily accessible to many browsers, mobile devices, etc. It also supports wide variety of media types including XML, JSON etc.
CREATE WEB API
To create Web API, following are the mentioned points:
Step 1:
Open Visual Studio-> Select Web application-> Select MVC and check Web API.
Step 2:
Add a model with name "Item"
public class Item
{
public int Id { get; set; }
public string Name { get; set; }
public string Category { get; set; }
public decimal Price { get; set; }
}
Step 3:
Add an ApiController with name "ItemController". Create functions to process like GetAllItems() which will return the list of all items and GetItems() which will return the item specified by the given id.
public class ItemController : ApiController
{
Item[] items = new Item[]
{
new Item{ Id =1, Name="A", Category="XYZ", Price=10 },
new Item{ Id =2, Name="B", Category="Test", Price=20 }
};
public IEnumerable<Item> GetAllItems()
{
return items;
}
public Item GetItems(int id)
{
var item = items.FirstOrDefault((p) => p.Id == id);
if (item == null)
{
return null;
}
return item;
}
}
Step 4:
Once all the code done, publish the Web API to some location.
HOST WEB API
To host Web API on IIS, following are the mentioned points.
Step 1:
Go to IIS (Hit inetmgr on run command)
Step 2:
Go to Sites then click on Add Web Site
Step 3:
Provide details for site to host
After this Web API will get host.
USE OF WEB API IN AN APPLICATION
Write the code to get the data from Web API. To deserialize the json use any Json dll. Here we are using Newtonsoft.Json. To get the the details of items create a class for it.
public class Item
{
public int Id { get; set; }
public string Name { get; set; }
public string Category { get; set; }
public double Price { get; set; }
}
and write the code as per given below
protected void Page_Load(object sender, EventArgs e)
{
List<Item> itemList =null;
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(ConfigurationManager.AppSettings.Get("API_URL"));
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.GetAsync("api/Item").Result ;
if (response.IsSuccessStatusCode)
{
var result = response.Content.ReadAsStringAsync().Result ;
itemList = JsonConvert.DeserializeObject<List<Item>>(result);
gvDetails.DataSource = itemList;
gvDetails.DataBind();
}
}
the output will be
Hope this will help you!
0 Comment(s)