Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

How to post jSON data to WebAPI using C#

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 .

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

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

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;
usingSystem.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.

  1. Void
  2. Primitive type or Complex type
  3. HttpResponseMessage
  4. 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;
usingSystem.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespaceWebApiDemo.Controllers
{
    public class HomeController : ApiController
    {
        public HttpResponseMessageSaveEmployee(Employee employee)
        {
            string Result = "Name: " + employee.Name + " Age: " + employee.Age;

            returnRequest.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;
usingSystem.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
usingSystem.Threading.Tasks;
usingSystem.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;


This post first appeared on ASPArticles, please read the originial post: here

Share the post

How to post jSON data to WebAPI using C#

×

Subscribe to Asparticles

Get updates delivered right to your inbox!

Thank you for your subscription

×