How to use Multiple POST GET DELETE in Web API Controller

If we are going to use multiple POST, GET or any HTTP verb in a single API controller, then it will throw an error due to ambiguity between the same verb methods . So, by considering this requirement, I have decided to write an article to explain why multiple Get and Post methods are not working and what routing configuration is required to use multiple GET and POST methods in a single Web API controller class.

All resources are accessed via the Base url+API+ApiController combination, which is defined by default in WebApiConfig.cs. For this reason, all resources are accessed using the controller name because inside the controller there is only one method defined which has the same HTTP verb like GET or POST . We can access the web API methods using the following url structure with this default routing pattern .

Consider our REST Service URL will be http://localhost:56290/api/Home which is described as follows,
  • http://localhost:56290: is the base address of web API service, It can be different as per your server.
  • API: It is the used to differentiate between Web API controller and MVC controller request .
  • Home: This is the Web API controller name.
Once we add another POST or Get method inside the API controller class with the same url routing structure, then accessing the specific method is very difficult due to the ambiguity between the two same HTTP verb methods.

Solution

To overcome the preceding mentioned issue and allow multiple GET and POST methods in a single web API controller class, you need to modify the url structure which is defined inside the WebApiConfig.cs as shown in the following image.

Now, with the preceding url pattern, we can access web API methods 
base url +API+Controller+webApi method.

E.g

http://localhost:56290/api/Home/AddEmployeeDetails 

From all the preceding examples and explanations, we have learned how to configure a web API routing template to use multiple GET POST methods in a single web API controller class.

Summary

I hope this article is useful for all readers. If you have any suggestions, then please mention them in the comment section.

Video : Creating ASP.NET Web API REST Service Step by Step

This video tutorial guide you step  by step to create ASP.NET Web API REST Service  which covers the following topics
  • Creating Web API REST Service Step by step.
  • Adding Web API Controller Class
  • Adding Model Class .
  • Configuring Web API routing .
  • Configuring Multiple Get POST methods inside the Web API controller .
  • Getting JSON Data From Service.
Now Let's watch 


Summary 
I hope this video tutorial is useful for all viewers , If you like this video then , don't forget to subscribe compilemode.com YouTube Channel.

SubScribe To Youtube Channel

Allow Multiple GET POST Methods in Single ASP.NET Web API Controller

Many reader asking me, How we use multiple GET, POST , PUT , Delete methods in single Web API Controller class since , If we are going use multiple POST or GET methods in single API controller then its not working . So by considering this requirement I have decided to write article to explain why multiple Get , Post methods are not working and what configuration we need to do So we can use multiple Get , POST methods in single Web API controller class.
Problem
The default URL structure of ASP.NET Web API defined into the WebApiConfig.cs file is like shown in the following Image.


In the Preceding routing structure, we can access the resource using Base url+API+ApiController which is by default defined in WebApiConfig.cs due of this reason all resources accessed using controller name because inside the controller not more than one method defined which having same HTTP verb like GET or POST . We can access the web API methods using following url structure with this default routing pattern .
 Consider our REST Service URL will be http://localhost:56290/api/Home which is described as follows,
  • http://localhost:56290: Is the base address of web API service, It can be different as per your server.
  • API: It is the used to differentiate between Web API controller and MVC controller request .
  • Home: This is the Web API controller name.
Once we add another POST or Get method inside the API controller class with same url routing structure then while accessing the specific method is very difficult due to the ambiguity between the two same HTTP verb method .
Solution
To overcome the preceding mentioned issue and allow multiple GET , POST methods in single web API controller class then you need to modify url structure which is defined inside the WebApiConfig.cs as shown in the following Image .

Now with preceding url pattern we can access web API methods base url +API+Controller+webApi method.
E.g
http://localhost:56290/api/Home/AddEmployeeDetails 
From all preceding examples and explanations we have learned how to use multiple GET POST methods in single web API controller class.
Summary
I hope this article is useful for all readers. If you have any suggestions, then please mention it in the comment section.

Display Data From DataBase in ASP.NET Using Web API And jQuey Json

I have often read the common question in forum posts as how to insert the ASP.Net form data into a database and display it using the Web API. So based on the this requirement, I have decided to write this article. Let us start creating an application so beginners can also understand.
Step 1 : Create Table and Stored Procedure
First create the table named Employee using the following script:
CREATE TABLE [dbo].[Employee](    
    [Id] [int] IDENTITY(1,1) NOT NULL,    
    [FirstName] [varchar](50) NULL,    
    [LastName] [varchar](50) NULL,    
    [Company] [varchar](50) NULL,    
 CONSTRAINT [PK_Employee] PRIMARY KEY CLUSTERED     
(    
    [Id] ASC    
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]    
) ON [PRIMARY]   
Now create a Stored Procedure to insert the data as:
Create Procedure [dbo].[InsertData]    
(    
@FName varchar(50),    
@Lname Varchar(50),    
@Compnay varchar(50)    
    
)    
as    
begin    
    
INSERT INTO [dbo].[Employee]    
           ([FirstName]    
           ,[LastName]    
           ,[Company])    
     VALUES    
           (    
           @FName,    
           @Lname,    
           @Compnay    
          )    
End 
Step 2 : Create Web Application
Now Let us create the sample web application as follows:
  1. "Start" -> "All Programs" -> "Microsoft Visual Studio 2010".
  2. "File" -> "New Project" -> "C#" -> "Empty Project" (to avoid adding a master page).
  3. Provide the website a name such as "DisplayingFormDataUsingWebAPI" or another as you wish and specify the location.
  4. Then right-click on the Solution Explorer -> "Add New Item" -> Add Web Form.
  5. Drag and drop three text boxes and one Button onto the <form> section of the Default.aspx page.
Now the default.aspx page source code will be as follows.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="InsertingFormDataUsingWebAPI.Default" %>      
          
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">      
          
    <html xmlns="http://www.w3.org/1999/xhtml">      
    <head id="Head1" runat="server">      
        <title>Article  by Vithal Wadje</title>      
             
    </head>      
    <body style="background-color:Navy;color:White">      
        <form id="form1" runat="server">      
        <br /><br />      
        <table>      
            <tr>      
                <td>      
                    First Name      
                </td>      
                <td>      
                    <asp:TextBox runat="server" ID="txtFirstName" />      
                </td>      
            </tr>      
            <tr>      
                <td>      
                    Last Name      
                </td>      
                <td>      
                    <asp:TextBox runat="server" ID="txtLastName" />      
                </td>      
            </tr>      
            <tr>      
                <td>      
                    Company      
                </td>      
                <td>      
                    <asp:TextBox runat="server" ID="txtCompany" />      
                </td>      
            </tr>      
            <tr>      
                <td>      
                </td>      
                <td>      
                    <asp:Button Text="Save" runat="server" ID="btnSave" />      
                </td>      
            </tr>      
        </table>      
        <br />      
              
        </form>      
    </body>      
    </html>  
Step 3 : Create Property Class
We have a .aspx Web form to insert the records. Now create the Property class named Employee class as in the following:
    public class Employee     
    {    
       public string FirstName { get; set; }    
       public string LastName { get; set; }    
       public string Company { get; set; }    
      
    }   
Step 4: Add Web API Controller Class
We created the preceding properties as in our table structure to insert the preceding employee details into the database. Now let us add a web API controller class into the web application by right-clicking on the project in the Solution Explorer and rename it EmpController with controller suffix.
Step 5: Create Repository Class to add and view records
Now add the following method into the Repository Class named AddEmployee and GetAllEmp that does all the data access related activities:
public IEnumerable<Employee> GetAllEmp()  
     {  
         connection();  
   
       com = new SqlCommand("select *from Employee", con);  
       com.CommandType = CommandType.Text;  
         SqlDataAdapter da = new SqlDataAdapter(com);  
         DataTable dt = new DataTable();  
         con.Open();  
         da.Fill(dt);  
         con.Close();  
  
         foreach (DataRow row in dt.Rows)  
         {  
             yield return new Employee  
             {  
                 Id = Convert.ToInt32(row["Id"]),  
                 FirstName = Convert.ToString(row["FirstName"]),  
                 LastName = Convert.ToString(row["LastName"]),  
                 Company = Convert.ToString(row["Company"]),  
  
             };  
         }  
  
     }  
     public string AddEmployees(Employee Emp)  
     {  
         connection();  
         com = new SqlCommand("InsertData", con);  
         com.CommandType = CommandType.StoredProcedure;  
         com.Parameters.AddWithValue("@FName", Emp.FirstName);  
         com.Parameters.AddWithValue("@Lname", Emp.LastName);  
         com.Parameters.AddWithValue("@Compnay", Emp.Company);  
         con.Open();  
         int i = com.ExecuteNonQuery();  
         con.Close();  
       
         if (i >= 1)  
         {  
             return "New Employee Added Successfully"; 
         }  
         else  
         {  
             return "Employee Not Added"; 
         }         
     }
 The entire EmpRepository class file will be as follows:
    using System;  
    using System.Collections.Generic;  
    using System.Linq;  
    using System.Web;  
    using System.Data.SqlClient;  
    using System.Configuration;  
    using System.Data;  
      
    namespace DisplayingFormDataUsingWebAPI  
    {  
        public class EmpRepository  
        {  
      
            private SqlConnection con;  
            private SqlCommand com;  
            
            private void connection()  
            {  
                string constr = ConfigurationManager.ConnectionStrings["getconn"].ToString();  
                con = new SqlConnection(constr);  
      
      
            }  
            public IEnumerable<Employee> GetAllEmp()  
            {  
                connection();      
              com = new SqlCommand("select *from Employee", con);  
              com.CommandType = CommandType.Text;  
                SqlDataAdapter da = new SqlDataAdapter(com);  
                DataTable dt = new DataTable();  
                con.Open();  
                da.Fill(dt);  
                con.Close();  
      
                foreach (DataRow row in dt.Rows)  
                {  
                    yield return new Employee  
                    {  
                        Id = Convert.ToInt32(row["Id"]),  
                        FirstName = Convert.ToString(row["FirstName"]),  
                        LastName = Convert.ToString(row["LastName"]),  
                        Company = Convert.ToString(row["Company"]),  
      
                    };  
                }  
      
            }  
            public string AddEmployees(Employee Emp)  
            {  
                connection();  
                com = new SqlCommand("InsertData", con);  
                com.CommandType = CommandType.StoredProcedure;  
                com.Parameters.AddWithValue("@FName", Emp.FirstName);  
                com.Parameters.AddWithValue("@Lname", Emp.LastName);  
                com.Parameters.AddWithValue("@Compnay", Emp.Company);  
                con.Open();  
                int i = com.ExecuteNonQuery();  
                con.Close();  
              
                if (i >= 1)  
                {  
                    return "New Employee Added Successfully";  
      
                }  
                else  
                {  
                    return "Employee Not Added";  
      
                }            
            }  
        }  
    } 
Step 6: Create Post and Get method
Create a Post and Get method in the ASP.Net Web API Controller Class.
Open the EmpController class that we created, delete the existing methods and create the AddEmployees and GetAllEmp method and call the EmpRepository class method as in the following:
    //creating the object of EmpRepository class  
          static EmpRepository repository = new EmpRepository();  
      
          public IEnumerable<Employee> GetAllEmp()  
          {  
              var users = repository.GetAllEmp();  
              return users;  
          }  
          public string AddEmployees(Employee Emp)  
          {  
              //calling EmpRepository Class Method and storing Repsonse   
              var response = repository.AddEmployees(Emp);  
              return response;  
      
          } 
You have seen that the preceding EmpController class is inherited from the ApiController class and we have created the method AddEmployee that calls the EmpRepository class method named AddEmployees. The entire EmpController class will be as follows:
    using System;  
    using System.Collections.Generic;  
    using System.Linq;  
    using System.Net;  
    using System.Net.Http;  
    using System.Web.Http;  
      
    namespace DisplayingFormDataUsingWebAPI  
    {  
        public class EmpController : ApiController  
        {  
      
            //creating the object of EmpRepository class  
            static EmpRepository repository = new EmpRepository();  
      
            public IEnumerable<Employee> GetAllEmp()  
            {  
                var users = repository.GetAllEmp();  
                return users;  
            }  
            public string AddEmployees(Employee Emp)  
            {  
                //calling EmpRepository Class Method and storing Repsonse   
                var response = repository.AddEmployees(Emp);  
                return response;  
      
            }  
      
        }  
    } 
Step 7: Call ASP.Net Web API Controller method
Call the ASP.Net Web API Controller method from the .aspx page using JSON.
Now we need to call the Web API controller method from the .aspx page. To do this we need to create a JSON method using jQuery as in the following:
    <script type="text/javascript">  
         function GetAllEmp() {  
               $.getJSON("api/Emp", function (data) {  
                   $('#bindemp').empty();  
                   $.each(data, function (key, val) {  
                     
                       var row = "<tr><td>" + val.Id + "</td> <td></td>  <td>" + val.FirstName + "  " + val.LastName + "</td> <td></td> <td>" + val.Company +  
                           "</td></tr>";  
      
                       $(row).appendTo($('#bindemp'));  
      
                   });  
               });  
           }        
           function AddEmp() {  
               
               var Emp = {};  
               Emp.FirstName = $("#txtFirstName").val();  
               Emp.LastName = $("#txtLastName").val();           
               Emp.Company = $("#txtCompany").val();  
      
               $.ajax({  
                   url:"<%=Page.ResolveUrl("/api/Emp/AddEmployees")%>",   
                   type: "POST",  
                   contentType: "application/json;charset=utf-8",  
                   data: JSON.stringify(Emp),  
                   dataType: "json",  
                   success: function (response) {  
      
                       alert(response);  
                    GetAllEmp();
                   },  
      
                   error: function (x, e) {  
                       alert('Failed');  
                       alert(x.responseText);  
                       alert(x.status);  
      
                   }  
               });  
           }
           $(document).ready(function ()  
            {  
      
              GetAllEmp();  
      
               $("#btnSave").click(function (e) {
                   AddEmp();  
                   e.preventDefault();
               });
           });  
      
       </script> 
Now the entire default.aspx page will be as follows:
    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="DisplayingFormDataUsingWebAPI.Default" %>  
      
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
      
    <html xmlns="http://www.w3.org/1999/xhtml">  
    <head id="Head1" runat="server">  
        <title>Article  by Vithal Wadje</title>  
        <script src="jquery-1.7.1.js" type="text/javascript"></script>  
          
        <script type="text/javascript">  
          function GetAllEmp() {  
                $.getJSON("api/Emp", function (data) {  
                    $('#bindemp').empty();  
                    $.each(data, function (key, val) {  
                      
                        var row = "<tr><td>" + val.Id + "</td> <td></td>  <td>" + val.FirstName + "  " + val.LastName + "</td> <td></td> <td>" + val.Company +  
                            "</td></tr>";  
      
                        $(row).appendTo($('#bindemp'));  
      
                    });  
                });  
            }  
             
            function AddEmp() {  
                
                var Emp = {};  
                Emp.FirstName = $("#txtFirstName").val();  
                Emp.LastName = $("#txtLastName").val();           
                Emp.Company = $("#txtCompany").val();  
      
                $.ajax({  
                    url:"<%=Page.ResolveUrl("/api/Emp/AddEmployees")%>",   
                    type: "POST",  
                    contentType: "application/json;charset=utf-8",  
                    data: JSON.stringify(Emp),  
                    dataType: "json",  
                    success: function (response) {  
      
                        alert(response);  
                     GetAllEmp();       
      
                    },  
                    error: function (x, e) {  
                        alert('Failed');  
                        alert(x.responseText);  
                        alert(x.status);  
                    }  
                });
      
            }
      
            $(document).ready(function ()  
             {
               GetAllEmp();
                $("#btnSave").click(function (e) {      
      
                    AddEmp();  
                    e.preventDefault();
                });
            });
        </script>  
    </head>  
    <body style="background-color:navy;color:White">  
        <form id="form1" runat="server">  
        <br /><br />  
        <table>  
            <tr>  
                <td>  
                    First Name  
                </td>  
                <td>  
                    <asp:TextBox runat="server" ID="txtFirstName" />  
                </td>  
            </tr>  
            <tr>  
                <td>  
                    Last Name  
                </td>  
                <td>  
                    <asp:TextBox runat="server" ID="txtLastName" />  
                </td>  
            </tr>  
            <tr>  
                <td>  
                    Company  
                </td>  
                <td>  
                    <asp:TextBox runat="server" ID="txtCompany" />  
                </td>  
            </tr>  
            <tr>  
                <td>  
                </td>  
                <td>  
                    <asp:Button Text="Save" runat="server" ID="btnSave" />  
                </td>  
            </tr>  
            </table>  
            <br />  
            <table>  
            
            <thead>  
                <tr>  
                    <td>  
                        Id  
                    </td>  
                   <td></td>  
                   
                    <td>  
                      Name  
                    </td>  
                     <td></td>  
                    <td>  
                        Company  
                    </td>  
                </tr>  
            </thead>  
           
            <tbody id="bindemp">  
            </tbody>  
        </table>  
        
        </form>  
    </body>  
    </html> 
Now run the application, the UI will be as follows:
 Now enter some records into the preceding fields and click on the Save button. Then the following screen shows the added records.
 
Now add another record.
 
Now you have seen how the insertion of records into the database and display it using Web API with Web Forms works.
Notes

  • Do a proper validation such as date input values when implementing.
  • Make the changes in the web.config file depending on your server details for the connection string.
Summary
You have learned here how to insert records into the database and display it using the ASP.Net Web API with Web Forms. I hope this article is useful for all readers. If you have a suggestion then please contact me.

www.CodeNirvana.in

Protected by Copyscape
Copyright © Compilemode