Header Ads

ASP.NET MVC: REST Web API POST Method

REST Web API is the most vital component for sharing data across multiple devices e.g. mobile devices, desktop applications or any website. The key element in developing & designing REST web API is to identify the type of methods that will eventual share the data across. The most popularly used method types are GET & POST.
Today, I shall be demonstrating creation of REST Web API POST type method using ASP.NET REST Web API platform.


Prerequisites:

Following are some prerequisites before you proceed any further in this tutorial:
  1. Knowledge of REST Web API.
  2. Knowledge of ASP.NET MVC5.
  3. Knowledge of C# Programming.
The example code is being developed in Microsoft Visual Studio 2019 Professional.The sample sales data is taken randomly from the internet.

Download Now!

Let's begin now.

1) Create new Web API project and name it "RESTWebApiPostMethod".  
2) Create "Controllers\WebApiController.cs" file.
3) Create "Post" method inside "Controllers\WebApiController.cs" file and replace following code in it i.e.

        #region POST api/WebApi

        /// <summary>
        /// POST api/WebApi
        /// </summary>
        /// <param name="postData">Post data parameter</param>
        /// <param name="request">Request parameter</param>
        /// <returns>Return - Response</returns>
        public HttpResponseMessage Post([FromBody]JToken postData, HttpRequestMessage request)
        {
            // Initialization
            HttpResponseMessage response = null;
            RequestObj requestObj = JsonConvert.DeserializeObject<RequestObj>(postData.ToString());
            DataTable responseObj = new DataTable();
            string json = string.Empty;

...
                // Loading Data.
...
                // Processing.
...
                // Settings.
                json = JsonConvert.SerializeObject(responseObj);
                response = Request.CreateResponse(HttpStatusCode.OK);
                response.Content = new StringContent(json, Encoding.UTF8, "application/json");

...
            // Info.
            return response;
        }

        #endregion

In the above code, a simple post method has been created which deserialize the input JSON data, then process the request query and finally, prepare & send the response JSON packet. There are few things in the above code that need to be taken care off i.e.
  1. The first point is name of our target POST/GET type method, know that in ASP.NET MVC platform, the advantage of writing REST Web API is that the platform take care of most of the things, the default names by convention in ASP.NET MVC REST Web API platform are "Post" for POST type method and "Get" for GET type method with method overloading with parameter variations, this is the reason developers do not explicitly need to write "HttpPost" data annotation/Attribute tag above POST type method to explicitly tells the platform that it is POST type method. However, if you need to change the default name of post/get method or you have more complex number of methods then you can utilize Method Name Routing technique to achieve your target name, but, follow the convention and use post/get as prefix with your method name.

  2. In the second point to understand how you want to send your input query data i.e. via URL parameters or via JSON. In the above sample, I am sending input query data via JSON structure. For complex input query data JSON structure is recommended and for simple one or two parameters URL form input data structure is preferred.

  3. In third point you need to deserialize your input request query and map the input request structure to a JSON object mapper if you are using JSON as input request structure.

  4. In the fourth and final point, you need to explicitly create your response packet to return JSON resultant data otherwise your direct JSON response might have slashes and improper string formatting causing dificult for your consumer application to consume the REST Web API.

4) Lets, test out REST Web API in action using REST Web API client. I am using Firefox plugin i.e. "RESTED". Execute the project and simply hit the REST Web API via URL directly as the REST Web API does not have any authorization and I will get following response i.e.


Conclusion

In this article, you will learn to create REST Web API POST type method using ASP.NET REST Web API platform. You will also learn about default behavior that ASP.NET MVC platform offers in respect to creating POST/GET type methods. You will learn about choosing right input request query type form i.e. either via URL parameter or via JSON. You will then learn to deserialize the input request data using JSON object mapper technique. You will also learn to properly create response packet with proper string formatting and finally, you will learn to test REST Web API using any REST client to see your REST Web API in action before consumption.

No comments