How to post jSON data to WebAPI using C#

 Print 
 Posted By :  ASPArticles
 Posted Date: Apr 21, 2018
 Category : 
 Post Hits : 161

In this article, I am going to explain you how to create a simple WebAPI application and post json data to WebAPI using C#. We will be using Visual Studio 2013 and .NET framework 4.5.

We will cover below topics.
1) Creating an empty WebAPI application.
2) Creating a web api method which takes complex data (Employee or Person...etc.) as input parameter and returns single string in response.
3) Passing jSON data to complex method in C# using Http WebRequest.
4) Passing jSON data to complex method in C# using HttpClient.

Creating Web API Empty Application

First step is to create ASP.NET Web API empty application as shown below.
Go to FileNewProject. A new window will be open as shown below.
Now go to Web and select .NET Framework 4.5 and give project name and click on OK .

Creating asp.net web api application

Now new window will open as shown below.
Now Select Empty Template, check on Web API checkbox and click on OK.

Selecting asp.net web api empty template

Now, a new project will be created as shown below.

Asp.net web api empty folder structure

Modify Web API Routing

Open WebApiConfig.cs file. Visual studio generates default routing as shown below. Add {action} in routeTemplate as highlighted in yellow.

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

namespace WebApiDemo
{
public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services

        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}
}

Adding API Controller

Next step is to add api controller to application. Go to Controller folder → Add → Controller.. → select 'Web API 2 Controller-Empty'. Give it's name HomeController and click on Add.
In home controller class, create a method SaveEmployee whick takes Employee object as input parameter and returns simple string.

WebAPI method supports below return types.

  • Void
  • Primitive type or Complex type
  • HttpResponseMessage
  • IHttpActionResult

We will be using HttpResponseMessage method type in this demo. With HttpResponseMessage, we can return response data (simple or complex objects) along with different status code like 202, 403, 404 as per our requirement.

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

namespace WebApiDemo.Controllers
{
    public class HomeController : ApiController
    {
        public HttpResponseMessage SaveEmployee( Employee employee)
        {
            string Result = "Name: " + employee.Name + " Age: " + employee.Age;

            return Request.CreateResponse( HttpStatusCode.OK, Result);
        }
    }
    public class Employee
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }
}

Passing jSON data to complex method in C# using Http WebRequest

Make sure webapi application is running. Now, create a C# console application and pass complex json data to WebAPI method using http WebRequest in C#.

Before passing complex objects, we need to serialize complex data into jSON object. For this you can use Json.NET - Newtonsoft or JavaScriptSerializer. In this demo, we will be using JavaScriptSerializer.

To use Json.NET, you can download dll from internet or you can add reference from nuget package manager.

To use JavaScriptSerializer, we need to add System.Web.Extensions assembly reference to client project.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Web.Script.Serialization;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Test test = new Test();
            string output = test.PassComplexData();
        }
    }
    public class Employee
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }
    public class Test
    {
        public string PassComplexData()
        {
            string ResponseString = "";
            HttpWebResponse response = null;
            try
            {
                var request = (HttpWebRequest)WebRequest.Create("http://localhost:32160/api/home/SaveEmployee");
                request.Accept = "application/json"; //"application/xml";
                request.Method = "POST";

                Employee obj = new Employee() { Name = "Rahul" , Age = 30 };
                JavaScriptSerializer jss = new JavaScriptSerializer();
                // serialize into json string
                var myContent = jss.Serialize(obj);

                var data = Encoding.ASCII.GetBytes(myContent);

                request.ContentType = "application/json";
                request.ContentLength = data.Length;

                using (var stream = request.GetRequestStream())
                {
                    stream.Write(data, 0, data.Length);
                }

                response = ( HttpWebResponse)request.GetResponse();

                ResponseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
            }
            catch (WebException ex)
            {
                if (ex.Status == WebExceptionStatus.ProtocolError)
                {
                    response = ( HttpWebResponse)ex.Response;
                    ResponseString = "Some error occured: " + response.StatusCode.ToString();
                }
                else
                {
                    ResponseString = "Some error occured: " + ex.Status.ToString();
                }
            }
            return ResponseString;
        }
    }
}

jSON OUTPUT:
Output can be seen below as json format.
"Name: Rahul Age: 30"

XML OUTPUT:
You can change response type from json to xml in accept parameter as shown below.
request.Accept = "application/json";

<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">
Name: Rahul Age: 30
</string>

Passing jSON data to complex method in C# using HttpClient

To use HttpClient, we need to add System.Net.Http assembly reference to client project and also to use JavaScriptSerializer, we need to add System.Web.Extensions assembly reference to client project.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using System.Web.Script.Serialization;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Test test = new Test();
            string output = test.PassComplexData().Result;
        }
    }
    public class Employee
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }

    public class Test
    {
        public async Task<string > PassComplexData()
        {
            string Response = "";
            try
            {
                HttpResponseMessage HttpResponseMessage = null;
                using (var httpClient = new HttpClient())
                {
                    httpClient.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("application/json"));
                    //application/xml

                    Employee obj = new Employee() { Name = "Rahul" , Age = 30 };
                    JavaScriptSerializer jss = new JavaScriptSerializer();
                    // serialize into json string
                    var myContent = jss.Serialize(obj);

                    var httpContent = new StringContent (myContent, Encoding .UTF8, "application/json");

                    HttpResponseMessage = await httpClient.PostAsync("http://localhost:32160/api/home/SaveEmployee", httpContent);

                    if (HttpResponseMessage.StatusCode == HttpStatusCode.OK)
                    {
                         Response = HttpResponseMessage.Content.ReadAsStringAsync().Result;
                    }
                    else
                    {
                        Response = "Some error occured." + HttpResponseMessage.StatusCode;
                    }
                }
            }
            catch (Exception ex)
            {

            }
            return Response;
        }
    }
}

OUTPUT:
Output will be same as http WebRequest as seen above.

Modifying HttpResponseMessage SaveEmployee Method

Till now, we were returning single string from web api method using HttpResponseMessage type. Now modify SaveEmployee as shown below to return complex data in json or xml format.

public class HomeController : ApiController
{
    public HttpResponseMessage SaveEmployee( Employee employee)
    {
        // string Result = "Name: " + employee.Name + " Age: " + employee.Age;
        Employee Result = new Employee() { Name = "Rahul" , Age = 30 };

        return Request.CreateResponse( HttpStatusCode.OK, Result);
    }
}
public class Employee
{
    public string Name { get; set; }
    public int Age { get; set; }
}

jSON OUTPUT:
{"Name":"Rahul","Age":30}

XML OUTPUT:

<Employee xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/WebApiDemo.Controllers">
  <Age>30</Age>
  <Name>Rahul</Name>
</Employee>



blog comments powered by Disqus