Wednesday, April 27, 2016

Step By Step : ASP.NET Web API without ASP.NET MVC

Hi,

Welcome to my blog. In this post we will see a brief overview of how to create an Empty API Controller without ASP.NET MVC and call the methods in controller from a HTML Page using JQuery.

Overview:
Today my friend/colleague was working on a task where he was trying read two numbers from two text boxes and display their sum in a HTML page and his aim was to use Web API and he asked me to look into it. Since I never looked into Web API. I found it interesting and started looking tutorials and to my surprise I found a lot of tutorials where everyone was basically using same example like GetMovies and GetProducts and were preaching same thing without any clear explanation of what is exactly happening on backstage. The point which confused me is that how GetAllMovies and GetMovie(int id) will map to a url and why cannot I have one method name in my ApiController and overload it so that my urls maps and call what I need.I did this and want to write this post so that who ever wants it can use it.

In this post we will see following
1) Create a Empty API Controller with ASP.NET MVC application
2) How to call methods in Empty API Controller using JQuery in an HTML page.

This is just one of the way which I followed  I am not saying this is the best and it doesnot have cons. My main aim is to share my experience so that it will be useful for the needy. I tried to make this post as much interesting as possible. Please excuse me for my grammatical errors and typos. I welcome your constructive comments and suggestions which helps in improving this post and my technical skills

Introduction:
Simply to say, ASP.NET Web API is a framework to create RESTFUL applications using .NET Framework. It does not need much configuration settings like WCF needs. We can build HTML services and reach more clients like browsers, tablet devices, and mobile devices. We can use XML or JSON or something else with these API by allowing us to create API or http based service or client endpoints.

Now let's start our work
For this article, I am using the following tools/technologies to develop a my sample application
Visual Studio 2013
C#
.NET Framework 4.5
JQuery

Our sample application will launch a HTML page in browser and will be like below



















I always have the habit of creating empty solution first and then work on it. Here also I did same thing. I created an empty visual studio solution titled "ASPNETWebApiDemo"
























In Solution Explorer, right click on soultion and click Add and then New Project as shown in below





















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 Web Application. Name the project "WebApiProject" and click OK as shown below

























In the New ASP.NET Project dialog, select the Empty template. Under "Add folders and core references for", make sure to select check Web API. Click OK as shown below


























Now your solution will look like below



















Add a Controller:
In Web API, a controller is an object that handles HTTP requests. The Web Api controllers inherit from ApiController unlike MVC controllers which inherit from Controller class. In Solution Explorer, right-click the Controllers folder. Select Add and then select Controller.


























In the Add Scaffold dialog, select Web API Controller - Empty. Click Add.

























In the Add Controller dialog, name the controller "DataController". Click Add.












The scaffolding creates a file named DataController.cs in the Controllers folder.

















Normally DataController.cs is opened if not double-click the file to open it. Add below code to it

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace WebApiProject.Controllers
{
    public class DataController : ApiController
    {
        [HttpGet]
        public string GetData()
        {
            return "Hello from Data Controller";
        }

        [HttpGet]
        public int GetData(string number1, string number2)
        {
            return Convert.ToInt32(number1) + Convert.ToInt32(number2);
        }

        [HttpGet]
        public string GetData(int age)
        {
            return string.Format("Your age is : " + age);
        }
    }
}


As you can see DataController.cs has 3 methods with same name GetData() but with different parameters. I will explain how these methods are called in below section

Call WebApi :
We will call Web API using JQuery. You can also use JavaScript to call Web API. In this section we will add an HTML page that uses AJAX to call the Web API ( different methods in DataController.cs).

In Solution Explorer, right-click the project and select Add, then select New Item.



























In the Add New Item dialog, select the Web node under Visual C#, and then select the HTML Page item. Name the page "DataPage.html"


























Replace everything in this file with the following:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>ASP.NET Web API DEMO</title>
</head>
<body>
    <div>
        Number 1:
        <input type="text" id="num1" />
        <br />
        Number 2:
        <input type="text" id="num2" />
        <br />
        <br />
        <input type="button" value="Add" onclick="addValues();" />
        <br />
        <br />
        Result
        <br />
        Addition : <span id="addResult"></span>
        <br />
        <br />
        <input type="button" value="Get Message" onclick="getMessage();" />
        <br />
        <br />
        Result
        <br />
        Message :  <span id="message"></span>
        <br />
        <br />
        <input type="button" value="Get Age" onclick="getAge();" />
        <br />
        <br />
        Result
        <br />
        Message :  <span id="ageMessage"></span>
    </div>

    <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js"></script>
    <script>
        function getMessage() {
            $('#message').text("");
            var uri = 'api/Data';
            $.getJSON(uri)
           .done(function (data) {
               $('#message').text(data);
           })
                .fail(function (jqXHR, textStatus, err) {
                    $('#message').text('Error: ' + err);
                });
        }

        function addValues() {
            $.ajax({
                url: "/api/Data",
                data: { number1: $('#num1').val(), number2: $('#num2').val() },
                type: "GET",
                contentType: "application/json;charset=utf-8",
                statusCode: {
                    200: function (data) {
                        $('#addResult').text(data);
                    },
                    404: function () {
                        alert("Not Found!");
                    }
                }
            });
        }

        function getAge() {
            $.ajax({
                url: "/api/Data",
                data: { age: "23" },
                type: "GET",
                contentType: "application/json;charset=utf-8",
                statusCode: {
                    200: function (data) {
                        $('#ageMessage').text(data);
                    },
                    404: function () {
                        alert("Not Found!");
                    }
                }
            });
        }
    </script>
</body>
</html>



Now lets see how the methods in DataController.cs are called. I hope you have some background knowlegde of JQuery.
Here I am demonstrating how to call Web API using JQuery in two ways
1) getJSON and
2) ajax 

1) GetData()
getMessage() is used to call this method using getJSON way. Here we need to create the uri in format of api/[controllername] in our case it will be api/data. In getMessage() we are not setting any data so the uri api/data will be mapped to GetData() method. In this we are using getJSON to call Web API

2) GetData(string number1, string number2)
addValues() is used to call this method using .ajax way. Here we need to create the uri in format of api/[controllername] in our case it will be api/data. Since GetData(string number1, string number2) is expecting some input parameters , in addValues() we need to setup data like below
data: { number1: $('#num1').val(), number2: $('#num2').val() }
so url and data when combined together will map to GetData(string number1, string number2)
url: "/api/Data",
data: { number1: $('#num1').val(), number2: $('#num2').val() },


IMPORTANT NOTE : Since GetData(string number1, string number2) is expecting number1 and number2 as names of parameters give same names in below line or else it wil try to match the first Get method and in our case it is GetData() and you will get wrong results
data: { number1: $('#num1').val(), number2: $('#num2').val() }


3) GetData(int age)
This is a same as above point. getAge() is used to call this method using .ajax way. Here we need to give exactly like below to match to GetData(int age) if not it will try to match the first Get method in our case GetData() and you will get wrong results
url: "/api/Data",
data: { age: "23" },


That's it. Build your application so that we donot have any errors. Then Run your application. If there are no errors then your DataPage will launch in your browser.

Give number1 and number2 some valid int values
Click Add so get sum. This is from GetData(string number1, string number2)
Click Get Message to get message. This is from GetData()
Click Get Age to get age. This is from GetData(int age)






































Conclusion:

In this article we learned how to create a ASP.NET Web API without ASP.NET MVC. We created a ApiController class that has overloaded methods.We also saw how we can call controller overloaded methods using JQuery's getJSON and ajax ways. We also saw how urls are mapped to overload methods in ApiController.

Please feel free to let me know your valuable and constructive comments and suggestions which can help me to make this article better and improve my technical and written skills. Last but not the least please excuse me for my grammar and typos.

Thanks and have a nice and wonderful day.