ASP.NET Web API in MVC tutorial

Introduction to ASP.NET Web API

ASP.NET Web API is one of new exciting feature of ASP.NET MVC 4. It is ideal framework for creating RESTful applications with .NET framework. It makes easy to build HTTP services and reach large number of clients like browsers and mobile devices. You can use XML or JSON or something else with these API. See more details on RESTful CRUD operations using ASP.NET Web API.

ASP.NET Web API allows you create api or http based service or client endpoints.yujo Although it comes with ASP.NET MVC4, it is much flexible framework to develop REST and AJAX API for HTML5, ASP.NET Web forms, client server desktop applications. Unlike WCF Web API does not required much configuration settings and you can host it in your own applications.


WCF or ASP.NET Web API

Below points can help you to choose WCF or ASP.NET Web API

  • If you want to create resource based services and need to take full advantage of HTTP like cache control for browsers, transfer different kind of content types like documents, images, HTML pages ASP.NET Web API should be selected.
  • If you have heterogeneous clients for same service and needs to call service using different protocols like netTCPBinding, netNamedPipeBinding, wsHttpBinding WCF is the obvious choice.
  • If you have special requirements like CallBackContract, One way communication or queuing then WCF should be selected.

In this article we will create a simple ASP.NET web api application in MVC. This application will read the data from Customers.xml file and show it on web page using jQuery.

Implementation of ASP.NET Web API in MVC

  1. Create new ASP.NET Web API

    Open visual studio and click on File -> New Project -> Select ASP.NET MVC4 Web Application
    Name the application as NorthwindWebApi
    From next window select Web API template and Razor as ViewEngine.
    New ASP.Net MVC4 Project
  2. Customer Model

    In ASP.NET MVC, Model manages properties and data of application and it contains all application logic like business logic, validation logic or data access logic. Model binders helps controller to keep its code cleanly separated from actual request and its environment. See more on ASP.NET MVC Application Request life cycle

    ASP.NET web api will produce serialized data of model to JSON, XML or some other format. It also writes HTTP Response messages with serialized data. Client can use GET verb to get data in specific format like JSON or XML by setting Accept header HTTP Request message.

    Create a new class in Model folder. Name it as Customer

    Customer Model will represent Customer entity from datastore. Add below properties to Model.
        namespace NorthwindWebApi.Models
        {
            public class Customer
            {
                public string CustomerID { get; set; }
                public string CompanyName { get; set; }
                public string City { get; set; }
            }
        }
                
  3. Customer ApiController

    The controllers in Web API inherits from ApiController class instead of Controller. The major difference between them is, actions from ApiController returns data and not Views. See difference between ApiController and Controller.
    Add Customer ApiController by right click on Controllers folder from Solution Explorer. Select Add -> Controller. Name it as CustomerController
    From next window select Empty Api Controller.
    ASP.NET Web API controller
    Add below code to CustomerController. It has two methods GetAllCustomers which returns all the customers from Customer.xml and GetCustomer which takes id as input parameter and return its customer details.
    using NorthwindWebApi.Models;
    using System.Xml.Linq;
    using System.Collections;  
    
    namespace NorthwindWebApi.Controllers
    {
        public class CustomerController : ApiController
        {
            public List<customer> GetAllCustomers()
            {            
                List<Customer> customers = new List<Customer>();
                 
                XDocument doc = XDocument.Load("C:\\Customers.xml");
    
                foreach (XElement element in doc.Descendants("DocumentElement")
                    .Descendants("Customer"))
                {
                    Customer customer = new Customer();
    
                    customer.CustomerID = element.Element("CustomerID").Value;
                    customer.CompanyName = element.Element("CompanyName").Value;
                    customer.City  = element.Element ("City").Value;
    
                    customers.Add(customer);   
                }
    
                return customers;
            }
    
            public Customer GetCustomer(int id)
            {
                Customer customer = new Customer();
    
                XDocument doc = XDocument.Load("C:\\Customers.xml");
                
                XElement element = doc.Element("DocumentElement")
                                    .Elements("Customer").Elements("CustomerID").
                                    SingleOrDefault(x => x.Value == id.ToString());
                
                if (element != null)
                {
                    XElement parent = element.Parent;
    
                    customer.CustomerID =
                            parent.Element("CustomerID").Value;
                    customer.CompanyName =
                            parent.Element("CompanyName").Value;
                    customer.City =
                            parent.Element("City").Value;
    
                    return customer;
                }
                else
                {
                    throw new HttpResponseException
                        (new HttpResponseMessage(HttpStatusCode.NotFound));
                }
            }
        }
    }
                
  4. Customer View

    As Web API does not return View or ActionResult, for this tutorial you can use default Index.cshtml under Views -> Home folder.
    Replace html from Index.cshtml with below code which shows all customers by retrieving JSON through jQuery call to Customer Web API.
    <div id="body">
    <section class="content-wrapper main-content clear-fix">
        <div>
            <h2>All Customers</h2>
        </div>
        <div>
            <table id="customers" style="border: 1px solid black;"  ></table> 
        </div>
            
    </section>
    </div>
    
    @section scripts {
    <script>
    
        var apiCustomers = 'api/customer';
        $(document).ready(function () {
            // Send an AJAX request
            var rows = '';
            $('#customers').empty();
    
            $.getJSON(apiCustomers,
                function (data) {
                    $.each(data, function (key, val) {
                        var customerURL = apiCustomers + '/' + val.CustomerID;
                        rows = rows + '<tr style="border: 1px solid black;"><td>  ' +
                        '<a style="color: Blue; font-weight:bold; font-size:15px"'
                           + 'href="' + customerURL + '">' + val.CustomerID + '</a>' +
                            '</td><td>' + val.CompanyName + 
                            '</td><td>' + val.City + '</td></tr>';
                    });
                    $('#customers').html(rows);
                });
        });
    </script>
    }
                

    It shows all the customers and link to each customer.
    ASP.NET Web API All Customers

    Now click on CustomerID link to see Customer details.

    ASP.NET Web API Get Customer Details
    As we haven't implemented any HTML view for customer details it shows customer details in browser. Depending on your browser it shows the customer details Chrome and Firefox will show xml whereas Internet Explorer will show it in JSON. It is because the request attribute Accept-headers send by browsers are different.

Download source code.



Jobs in Ashburn


Web Developers - Robert Half Technology
.00 per year Sr. C#/SQL .NET Web (REST) Developer up to $130k +10% Bonus - Vienna, VA Job Overview ... development with Asp.Net, Ajax, CSS and...
 
Database Administrators - TierPM AV/IT Talent Solutions
Administrator in the Washington, DC area. The ideal candidate will have at least 5 years of SQL database ... 5-7 years of SQL DBA experience...
 
Computer Systems Analysts - Temporaries Now, INC
SDLC - .NET - TFS - SQL - Visual Studio - SOA - ASP.net - MS Team Foundation Server - Customer ... - SOA, ASP.net, MS Team Foundation Server,...
 
Computer Software Engineers, Applications - Strongbridge
is a highlyskilled ASP.NET/C# developer with a minimum of 5 years of experience including astrong ... preferred. 4-5 years of experience working...
 
Computer Software Engineers, Applications -
IT .Net Developer (Information Technology – C#/SQL) Job Description We are seeking an ... the concept of modular design IT .Net Developer (...






Latest Blogs on Dotnetmentors.com


Hello World Example With AngularJS and ASP.NET MVC
This article equips you to create your first hello world example using AngularJS framework and ASP.NET MVC.
 
How to Use Areas in ASP.NET MVC
This article describe about Areas in ASP.NET MVC application and organize application structure in better and simple way.
 
Explain ASP.Net MVC Routing With Example
This article describes how ASP.NET MVC routing works, Custom Routes, attribute routing, route constraints, Area Routing
 
ASP.NET MVC Application Request life cycle
This article describes about ASP.NET MVC request life cycle, it explains how request
 
Implementing Finalize and Dispose(.NET Framework) in C#
This article describes about implementing between dispose and finalize methods for


Speak your mind :
Leave a comment for this article on dotnetbloogers.com