Web API With AJAX: Understand Method Name and Attribute in Web API

This is the "Web API with AJAX" article series. This series is explaining various important concepts related to the Web API and AJAX operations. You can visit our previous explanations here:

This article explains action names and various attributes of them as well as the behavior actions corresonding to various attributes.

Action name does not make sense

Let's start with one of my small actual experiences. When I was just beginning to learn the Web API , one of my colleagues (from whom I had learned  the term Web API) told me that at time of a create action in the Web API we need to provide a matching name with a HTTP verb. How? If we specify a HttpPost attribute on any action then we need to provide the action name as Post(). But the concept is totally wrong. We can choose an action name of our own. In the following example we have specified the HttpGet() attribute and chosen Post() as the action name and obviously it will work smoothly.  Here is the implementation of the client code.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="APICall.aspx.cs" Inherits="WebApplication1.APICall" %>

<head runat="server">
   
<script src="jquery-1.7.1.js" type="text/javascript"></script>
    
<script>
         $(document).ready(
function () { 
             $(
"#Save").click(function () {
                 $.ajax({

                     url:
'http://localhost:3413/api/person',
                     type:
'GET',
                     dataType:
'json',
                     success:
function (data, textStatus, xhr) {
                         console.log(data);

                     },

                     error:
function (xhr, textStatus, errorThrown) {
                         console.log(
'Error in Operation');
                     }

                 });

             });

         });

   
</script>
</
head>
<
body>
    
<input type="button" id="Save" value="Save Data" />
</
body>
</
html>

We are seeing that we are making a GET request to the ajax() function. Here is the implementation of the Web API and we are seeing that the HttpGet attribute is specified on top of the Post() action. 

using System;

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

namespace
WebApplication1.WebAPI
{

    public class personController : ApiController
   {

        [
HttpGet]
       
public String Post()
        {

           
return "Post method in HttpGet attribute";
        }

    }

}

Here is the output of the above example.

Action name

Not even for a Get() and Post() are we allowed to provide any name as the action name. Here we have chosen "PostAction" as the action name.

public class personController : ApiController

{

    [HttpGet]

    public String PostAction()
    {

        
return "Post method in Diffrent Name";
    }

}

Use ActionName attribute

We can use the "ActionName" attribute to specify any name for a specific action. In this example we will see how to implement it. Here is an implementation of the client code.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="APICall.aspx.cs" Inherits="WebApplication1.APICall" %>

<head runat="server">
   
<script src="jquery-1.7.1.js" type="text/javascript"></script>
    
<script>
         $(document).ready(
function () { 
             $(
"#Save").click(function () {
                 $.ajax({

                     url:
'http://localhost:3413/api/person/MyPostAction',
                     type:
'GET',
                     dataType:
'json',
                     success:
function (data, textStatus, xhr) {
                         console.log(data);

                     },

                     error:
function (xhr, textStatus, errorThrown) {
                         console.log(
'Error in Operation');
                     }

                 });

             });

         });

   
</script>
</
head>
<
body>
   
<form name="form1" id="form1">
       
<input type="button" id="Save" value="Save Data" />
   
</form>
</
body>
</
html> 

We are seeing that the phrase "MyPostAction" is added at the very last to the URL. Here is the implementation of the Web API.

using System;

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

namespace
WebApplication1.WebAPI

    public class personController : ApiController

    {
        [
HttpGet]
        [
ActionName("MyPostAction")]
       
public String GetAction()
        {

           
return "Get Method with Action Name";
        }
 
    }

}
 

We are specifying the "ActionName" attribute on top of the GetAction(). Here is sample output.
 

Action Attribute

NonAction attribute to prevent call from client
 

We can specify the NonAction attribute on top of any action that implies that the action cannot be accessed from the client part. In this example we will try to call "MyPostAction".

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="APICall.aspx.cs" Inherits="WebApplication1.APICall" %>

<head runat="server">
   
<script src="jquery-1.7.1.js" type="text/javascript"></script>
    
<script>
         $(document).ready(
function () { 
             $(
"#Save").click(function () {
                 $.ajax({

                     url:
'http://localhost:3413/api/person/MyPostAction',
                     type:
'GET',
                     dataType:
'json',
                     success:
function (data, textStatus, xhr) {
                         console.log(data);

                     },

                     error:
function (xhr, textStatus, errorThrown) {
                         console.log(
'Error in Operation');
                     }

                 });

             });

         });

   
</script>
</
head>
<
body>
   
<input type="button" id="Save" value="Save Data" />
</
body>
</
html> 

We are seeing that the "MyPostAction" is specified with the NonAction attribute. So, it's not possible to call it from an external application.

using System;

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

namespace WebApplication1.WebAPI

    public class personController : ApiController

    {
        [
HttpGet]
        [
NonAction]
        [
ActionName("MyPostAction")]
       
public String GetAction()
        {

           
return "Get Method with Action Name";
        }
 
    }

} 

We are experiencing an error at the time of an action call.
 

NonAction attribute
ActiveVerb attribute to restrict action for specific verbs

We can use the "ActiveVerb" attribute to allow certain verbs to consume a service from a certain action. In the following example we are allowing a POST verb to certain controller and we are trying to consume it using the GET verb. Have a look at the following example.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="APICall.aspx.cs" Inherits="WebApplication1.APICall" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
   
<script src="jquery-1.7.1.js" type="text/javascript"></script>


    
<script>
         $(document).ready(
function () { 
             $(
"#Save").click(function () {                
                 $.ajax({

                     url:
'http://localhost:3413/api/person',
                     type:
'GET',
                     dataType:
'json',
                     success:
function (data, textStatus, xhr) {
                         console.log(data);

                     },

                     error:
function (xhr, textStatus, errorThrown) {
                         console.log(
'Error in Operation');
                    }

                 });

             });

         });

   
</script>
</
head>
<
body>
   
<input type="button" id="Save" value="Save Data" />
</
body>
</
html> 

Here is the implementation of the Web API.

using System;

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

namespace
WebApplication1.WebAPI

    public class personController : ApiController

    {       

        [AcceptVerbs("POST")]

        public String GetAction()
        {

           
return "Get Method with Action Name";
        }

    }

}

We are seeing that the GET request cannot consume the GetAction() action because it only accepts a POST verb.
 

ActiveVerb attribute
Allow multiple verbs in single action

We can allow multiple verbs to single action. In this example we are allowing the GET and POST verbs to the GetAction controller.

public class personController : ApiController

{
    [
AcceptVerbs("GET","POST")];
   
public String GetAction()
    {

       
return "Get Method with Action Name";
    }

} 

Conclusion

In this article we have learned various attributes of actions in the Web API. It will be very helpful in daily programming life. Hope you get some new ideas from this article.

Up Next
    Ebook Download
    View all
    Learn
    View all