Category Archives: ASP.Net Web API

Multiple actions were found that match the request Web API.

When we create a Web API, it creates a default route “api/{controller}/{id}” in WebApiConfig.cs file. Action name is not defined in the route.

Web API by default serves to HTTP verbs Get, Post, Put, Delete with optional parameters.

// GET api/values
public IEnumerable<string> Get()
{
    return new string[] { "value1", "value2" };
}

// GET api/values/5
public string Get(int id)
{
    return "value";
}

//POST api/values
public void Post([FromBody]string value)
{
}

// PUT api/values/5
public void Put(int id, [FromBody]string value)
{
}

// DELETE api/values/5
public void Delete(int id)
{
}


Web API identifies the action with http verbs. If we have more than one action method with same HTTP verb and same parameters then it is very difficult for web api to serve the correct method. So it returns the error message “Multiple actions were found that match the request”.

Multiple actions were found that match the request Web API

Multiple actions were found that match the request Web API

To resolve this confusion we have to define “action” in the route as “api/{controller}/{action}/{id}”.

[HttpPost]
public void AddEmployee(Employee value)
{
    // return emp;
}


Now it will be able to identify AddEmployee action method.

Get address from latitude and longitude using google map api

We can find address components Country, State, Postal code etc. from latitude and longitude using google map api.
For this google provide a service. We have to call this service using post method. Service return result in two formats xml or json based on the parameter passed as xml or json.

using System.Xml;
public void GetAddressFromLatLon(Decimal Latitude, Decimal Longitude)
{
    string result = null;
    System.Net.WebClient webClient = new System.Net.WebClient();
    var apiUrl = "https://maps.googleapis.com/maps/api/geocode/xml?latlng=" + Latitude + "," + Longitude + "&sensor=false";
    var searchRequest = "";
    webClient.Headers.Add("content-type", "application/x-www-form-urlencoded");
    result = webClient.UploadString(apiUrl, searchRequest);
    XmlDocument xbook = new XmlDocument();
    xbook.LoadXml(result);
    string CountryCode = string.Empty;
    string CountryName = string.Empty;
    string StateCode = string.Empty;
    string stateName = string.Empty;
    foreach (XmlNode node in xbook.DocumentElement.ChildNodes)
    {
        if (node.Name == "result")
        {
            foreach (XmlNode node1 in node)
            {
                if (node1.Name == "address_component")
                {
                    foreach (XmlNode node2 in node1)
                    {
                        if (node2.Name == "type" && node2.InnerText == "country")
                        {
                            foreach (XmlNode node3 in node1)
                            {
                                if (node3.Name == "long_name")
                                {
                                    CountryName = node3.InnerText;
                                }
                                else if (node3.Name == "short_name")
                                {
                                    CountryCode = node3.InnerText;
                                }
                            }
                        }
                        if (node2.Name == "type" && node2.InnerText == "administrative_area_level_1")
                        {
                            foreach (XmlNode node3 in node1)
                            {
                                if (node3.Name == "long_name")
                                {
                                    stateName = node3.InnerText;
                                }
                                else if (node3.Name == "short_name")
                                {
                                    StateCode = node3.InnerText;
                                }
                            }
                        }
                    }
                }
            }
            break;
        }
    }
}


Call the service by passing Latitude and Longitude.

Decimal Latitude = Convert.ToDecimal(50.95846878);
Decimal Longitude = Convert.ToDecimal(6.97181002);
GetAddressFromLatLon(Latitude, Longitude);

Security in ASP.NET Web API.

Security can be provide in ASP.Net Web API using Authentication and Authorization.
Authentication means user identity to the system. user is able to login to a website. Example Google Account.
Authentication is provided using HTTP Module and HTTP Message Handler.

HTTP Module- You can configure your project to IIS to use built in authentication i.e; HTTP Module. It uses IPrincipal object for security under which your project is running. You can get the user identity in Thread.CurrentPrincipal. If Identity.IsAuthenticated is true then user is authenticated else user is not authenticated. It is only available to web-hosting.

HTTP Message Handler- This is more flexible as compared to HTTP Module. It can be used with both self-hosting and web-hosting. It filters all the request and pass only request that are requesting to web API route. we can provide different message handlers to different routes. we can get the identity in Thread.CurrentPrincipal.

Authorization means user rights. user is able to read and not allowed to write. Authorization is provided using Authorization Filters. We can provide filters at different level. Filters are called before any controller action.

At Global Level-  We can set filter in global file WebApiConfig.cs. This filter will authorize all the Controllers.

public static void Register(HttpConfiguration config)
{
    config.Filters.Add(new AuthorizeAttribute());
}


At Controller Level-  We can specify filters to specific Controllers. This filter will authorize all the Controller actions.

[Authorize]
public class EmployeeController : ApiController
{
    public List<Employee> Get()
    {
        return EmployeeDAL.GetAllEmployees();
    }
    public Employee Get(string id)
    {
        return EmployeeDAL.GetEmployee(id);
    }    
}


At Action Level-  We can specify filters at action level. This filter will authorize specific action.

public class EmployeeController : ApiController
{
    [Authorize]
    public List<Employee> Get()
    {
        return EmployeeDAL.GetAllEmployees();
    }
    public Employee Get(string id)
    {
        return EmployeeDAL.GetEmployee(id);
    }    
}


Inside Action Method-  We can customize action return result based on conditions.

public class EmployeeController : ApiController
{    
    public List<Employee> Get()
    {
       if (User.IsInRole("Manager"))
        {
          return EmployeeDAL.GetAllEmployees();
        }      
       else
        {
          //return different result
        }
    }      

    [Authorize(Users="Hitesh,Dev")] //This Action will be available for these users.
    public Employee Get(string id)
    {
        return EmployeeDAL.GetEmployee(id);
    }    
}

CRUD Operations using ASP.NET Web API.

This Tutorial will explain how to implement crud operations using ASP.NET Web API.

Open Visual Studio 2012. Go to create new project tab. Select “Asp.Net MVC 4 Web Application.” Then select Web API from Project Template.

using ASP.NET Web API Crud operation are performed by

GET – To Get data from database
POST – To Insert data into database
PUT – To Update data into database
DELETE – To delete data in database

Create an Employee class in Model folder. And write the below code in the file.

public class Employee
{
    [Display(Name = "Employee ID")]
    public string EmployeeID { get; set; }
    [Display(Name = "First Name")]
    public string FirstName { get; set; }
    [Display(Name = "Last Name")]
    public string LastName { get; set; }

    [DataType(DataType.Date)]
    [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
    [Display(Name = "Date of Birth")]
    public string DOB { get; set; }

    public string Gender { get; set; }
    public string Nationality { get; set; }
    public string Language { get; set; }
    public string Address { get; set; }
}


Create an EmployeeController Controller file in Controller folder. And write the below code in the file.

public class EmployeeController : ApiController
{
    public List<Employee> Get()
    {
        return EmployeeDAL.GetAllEmployees();
    }
    public Employee Get(string id)
    {
        return EmployeeDAL.GetEmployee(id);
    }
    public void Post(Employee Employee)
    {
        EmployeeDAL.AddEmployee(Employee);
    }
    public void Put(Employee Employee, string id)
    {
        EmployeeDAL.UpdateEmployee(Employee, id);
    }
    public void Delete(string id)
    {
        EmployeeDAL.RemoveEmployee(id);
    }
}


Create a EmployeeDAL file in Model folder for DataBase Operations.

 public class EmployeeDAL
    {
        private static List<Employee> employees;

        public static List<Employee> GetAllEmployees()
        {            
            try
            {
               // Code to fetch data from database
               // create employee list and return
               // return employees;
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }
        public static Employee GetEmployee(string employeeID)
        {           
            try
            {
                // Code to fetch data from database based on employeeID
                // create list and return                           
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public static void RemoveEmployee(string employeeID)
        {           
            try
            {
                // Code to delete record from database based on employeeID                              
            }
            catch (SqlException ex)
            {
                throw ex;
            }           
        }
        public static void AddEmployee(Employee employee)
        {            
            try
            {    
                 // Code to Insert employee data into database         
            }
            catch (SqlException ex)
            {
                throw ex;
            }            
        }
        public static void UpdateEmployee(Employee employee, string id)
        {           
            try
            {
                 // Code to update employee data into database             
            }
            catch (SqlException ex)
            {
                throw ex;
            }            
        }
    }


Open Index.cshtml file in View folder. And replace body code with the code below.

<div id="body">
    <section class="featured">
        <div class="content-wrapper">
        </div>
        <div class="content-wrapper main-content clear-fix">
            <h2>Search</h2>
            @model WebApiPart1.Models.Employee
            @using (Html.BeginForm())
            {
                @Html.ValidationSummary(true)
                <fieldset>
                    <legend>Employee Search</legend>
                    <div class="editor-label">
                        @Html.LabelFor(model => model.EmployeeID)
                    </div>
                    <div class="editor-field">
                        @Html.TextBox("SearchEmployee")
                        @Html.ValidationMessageFor(model => model.EmployeeID)
                    </div>
                    <p>
                        <input type="submit" value="Search" onclick="SearchEmployeeById(); return false;" />
                        <input type="submit" value="Get ALL" onclick="GelAllEmployees(); return false;" />
                    </p>
                </fieldset>
                <h2>Employee List</h2>
                <table border="1" id="employees">
                    <thead>
                        <tr>
                            <th><b>Employee ID</b></th>
                            <th><b>First Name</b></th>
                            <th><b>Last Name</b></th>
                            <th><b>DOB</b></th>
                            <th><b>Gender</b></th>
                            <th><b>Nationality</b></th>
                            <th><b>Language</b></th>
                            <th><b>Address</b></th>
                            <th><b>Edit</b></th>
                            <th><b>Delete</b></th>
                        </tr>
                    </thead>
                    <tbody></tbody>
                </table>
                <h2>Create</h2>
                <fieldset>
                    <legend>Employee</legend>
                    <div class="editor-label">
                        @Html.LabelFor(model => model.EmployeeID)
                    </div>
                    <div class="editor-field">
                        @Html.EditorFor(model => model.EmployeeID)
                        @Html.ValidationMessageFor(model => model.EmployeeID)
                    </div>

                    <div class="editor-label">
                        @Html.LabelFor(model => model.FirstName)
                    </div>
                    <div class="editor-field">
                        @Html.EditorFor(model => model.FirstName)
                        @Html.ValidationMessageFor(model => model.FirstName)
                    </div>

                    <div class="editor-label">
                        @Html.LabelFor(model => model.LastName)
                    </div>
                    <div class="editor-field">
                        @Html.EditorFor(model => model.LastName)
                        @Html.ValidationMessageFor(model => model.LastName)
                    </div>

                    <div class="editor-label">
                        @Html.LabelFor(model => model.DOB)
                    </div>
                    <div class="editor-field">
                        @Html.EditorFor(model => model.DOB)
                        @Html.ValidationMessageFor(model => model.DOB)
                    </div>

                    <div class="editor-label">
                        @Html.LabelFor(model => model.Gender)
                    </div>
                    <div class="editor-field">
                        @Html.EditorFor(model => model.Gender)
                        @Html.ValidationMessageFor(model => model.Gender)
                    </div>

                    <div class="editor-label">
                        @Html.LabelFor(model => model.Nationality)
                    </div>
                    <div class="editor-field">
                        @Html.EditorFor(model => model.Nationality)
                        @Html.ValidationMessageFor(model => model.Nationality)
                    </div>

                    <div class="editor-label">
                        @Html.LabelFor(model => model.Language)
                    </div>
                    <div class="editor-field">
                        @Html.EditorFor(model => model.Language)
                        @Html.ValidationMessageFor(model => model.Language)
                    </div>

                    <div class="editor-label">
                        @Html.LabelFor(model => model.Address)
                    </div>
                    <div class="editor-field">
                        @Html.EditorFor(model => model.Address)
                        @Html.ValidationMessageFor(model => model.Address)
                    </div>
                    <p>
                        <input type="submit" id="AddUpdate" name="AddUpdate" value="Create" onclick="ADDUpdate(); return false;" />
                        <input type="submit" id="Clear" name="Clear" value="Clear" onclick="ClearForm(); return false;" />
                    </p>
                </fieldset>
            }
        </div>
    </section>
</div>

Asp.Net Web API

Asp.Net Web API

Get ALL Employee List using GET method.

 function GelAllEmployees() {
 $.ajax({
 type: "GET",
 url: "api/Employee",
 contentType: "json",
 dataType: "json",
 success: function (data) {
 $('#employees tbody tr').empty();
 $.each(data, function (key, value) {
 //stringify
 var jsonData = JSON.stringify(value);
 //Parse JSON
 var objData = $.parseJSON(jsonData);
 var id = objData.EmployeeID;
 var fname = objData.FirstName;
 var lname = objData.LastName;
 var dob = objData.DOB;
 var Gender = objData.Gender;
 var Nationality = objData.Nationality;
 var Language = objData.Language;
 var Address = objData.Address;
 $('
<tr>
<td>' + id + '</td>
<td>' + fname +
 '</td>
<td>' + lname + '</td>
<td>' + dob + '</td>
<td>' + Gender + '</td>
<td>' + Nationality + '</td>
<td>' + Language +
 '</td>
<td>' + Address + '</td>
<td><a onclick="GetEmployeeById(id); return false;" id="' + id + '" >Edit</a></td>
<td><a onclick="DeleteEmployee(id);" id="' + id + '" >Delete</a></td>
</tr>

').appendTo('#employees tbody');
 });
 },
 error: function (xhr) {
 alert(xhr.responseText);
 }
 });
 };


Get Employee by ID

 function GetEmployeeById(EmployeeID) {
    var employeeData = {
        "EmployeeID": EmployeeID
    };
    $.ajax({
        type: "GET",
        url: "api/Employee/" + employeeData.EmployeeID,
        contentType: "json",
        dataType: "json",
        success: function (data) {
            //stringify
            var jsonData = JSON.stringify(data);
            //Parse JSON
            var objData = $.parseJSON(jsonData);
            if (objData == null) {
                return;
            }
            $('#AddUpdate').val("Update");            
            $('#EmployeeID').val(objData.EmployeeID);
            $('#FirstName').val(objData.FirstName);
            $('#LastName').val(objData.LastName);
            $('#DOB').val(objData.DOB);
            $('#Gender').val(objData.Gender);
            $('#Nationality').val(objData.Nationality);
            $('#Language').val(objData.Language);
            $('#Address').val(objData.Address);
        },
        error: function (xhr) {
            alert(xhr.responseText);
        }
    });
}       


Search Employee by Employee ID

 function SearchEmployeeById() {
            var employeeData = {
                "EmployeeID": $('#SearchEmployee').val()
            };
            if (employeeData.EmployeeID == "") {
                return false;
            }
            $.ajax({
                type: "GET",
                url: "api/Employee/" + employeeData.EmployeeID,
                contentType: "json",
                dataType: "json",
                success: function (data) {
                    //stringify
                    $('#employees tbody tr').empty();
                    var jsonData = JSON.stringify(data);
                    //Parse JSON
                    var objData = $.parseJSON(jsonData);
                    if (objData == null) {
                        return;
                    }
                    var id = objData.EmployeeID;
                    var fname = objData.FirstName;
                    var lname = objData.LastName;
                    var dob = objData.DOB;
                    var Gender = objData.Gender;
                    var Nationality = objData.Nationality;
                    var Language = objData.Language;
                    var Address = objData.Address;
                    $('
<tr>
<td>' + id + '</td>
<td>' + fname +
                    '</td>
<td>' + lname + '</td>
<td>' + dob + '</td>
<td>' + Gender + '</td>
<td>' + Nationality + '</td>
<td>' + Language +
                    '</td>
<td>' + Address + '</td>
<td><a onclick="GetEmployeeById(id); return false;" id="' + id + '" >Edit</a></td>
<td><a onclick="DeleteEmployee(id); return false;" id="' + id + '" >Delete</a></td>
</tr>

').appendTo('#employees tbody');

                },
                error: function (xhr) {
                    alert(xhr.responseText);

                }
            });
        }


Add New Employee

 function AddNewEmployee() {
            var employeeData = {
                "EmployeeID": $('#EmployeeID').val(),
                "FirstName": $('#FirstName').val(),
                "LastName": $('#LastName').val(),
                "DOB": $('#DOB').val(),
                "Gender": $('#Gender').val(),
                "Nationality": $('#Nationality').val(),
                "Language": $('#Language').val(),
                "Address": $('#Address').val()
            };

            $.ajax({
                type: "POST",
                url: "api/Employee",
                data: JSON.stringify(employeeData),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                processData: true,
                success: function (data, status, jqXHR) {
                    alert("Successsfully added…. " + employeeData.EmployeeID);
                    GelAllEmployees();
                    ClearForm();
                },
                error: function (xhr) {
                    alert(xhr.responseText);
                }
            });
        }


Update Employee

function UpdateEmployee() {
            var employeeData = {
                "EmployeeID": $('#EmployeeID').val(),
                "FirstName": $('#FirstName').val(),
                "LastName": $('#LastName').val(),
                "DOB": $('#DOB').val(),
                "Gender": $('#Gender').val(),
                "Nationality": $('#Nationality').val(),
                "Language": $('#Language').val(),
                "Address": $('#Address').val()
            };
            $.ajax({
                type: "PUT",
                url: "api/Employee/" + employeeData.EmployeeID,
                data: JSON.stringify(employeeData),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                processData: true,
                success: function (data, status, jqXHR) {
                    alert("Successfully updated…" + employeeData.EmployeeID);
                },
                error: function (xhr) {
                    alert(xhr.responseText);
                }
            });
        }


Delete Employee

function DeleteEmployee(EmployeeID) {
            var txt;
            var r = confirm("Are you sure you want to delete this recored?");
            if (r == true) {
                $.ajax({
                    type: "DELETE",
                    url: "api/Employee/" + EmployeeID,
                    contentType: "json",
                    dataType: "json",
                    success: function (data) {
                        alert("Successsfully deleted…. " + EmployeeID);
                    },
                    error: function (xhr) {
                        alert(xhr.responseText);
                    }
                });
                GelAllEmployees();
            } else {
            }
        }


Clear form

  function ClearForm() {
            $('#EmployeeID').val("");
            $('#FirstName').val("");
            $('#LastName').val("");
            $('#DOB').val("");
            $('#Gender').val("");
            $('#Nationality').val("");
            $('#Language').val("");
            $('#Address').val("");
            $('#AddUpdate').val("Create");
        }


Create or Update decider function

  function ADDUpdate() {
            var btn = $('#AddUpdate').val();
            if (btn == "Create") {
                AddNewEmployee();
            }
            if (btn == "Update") {
                UpdateEmployee();
            }
        }


Add this script to get reference of JQuery.

 <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js"></script>