Saturday, 26 September 2015

Passing multiple complex type parameters to ASP.NET Web API



Asp.Net Web API introduces a new powerful REST API which can be consuming by a broad range of clients including browsers, mobiles, iphone and tablets. It is focused on resource based solutions and HTTP verbs.
Asp.Net Web API has a limitation while sending data to a Web API controller. In Asp.Net Web API you can pass only single complex type as a parameter. But sometimes you may need to pass multiple complex types as parameters, how to achieve this?
You can also achieve this task by wrapping your Supplier and Product classes into a wrapper class and passing this wrapper class as a parameter, but using this approach you need to make a new wrapper class for each actions which required complex types parameters. In this article, I am going to explain another simple approach using ArrayList.
Let's see how to achieve this task. Suppose you have two classes - Supplier and Product as shown below -
public class Product
{
public int ProductId { get; set; }
       public string Name { get; set; }
       public string Category { get; set; }
       public decimal Price { get; set; }
}

public class Supplier
{
public int SupplierId { get; set; }
       public string Name { get; set; }
       public string Address { get; set; }
}
In your Asp.Net MVC controller you are calling your Web API and you need to pass both the classes objects to your Web API controller.

Method 1: Using ArrayList
For passing multiple complex types to your Web API controller, add your complex types to ArrayList and pass it to your Web API actions as given below-
public class HomeController : Controller
{
public ActionResult Index()
        {
            HttpClient client = new HttpClient();
            Uri baseAddress = new Uri("http://localhost:2939/");
            client.BaseAddress = baseAddress;

            ArrayList paramList = new ArrayList();

            Product product = new Product { ProductId = 1, Name = "Book", Price = 500, Category = "Soap" };
            Supplier supplier = new Supplier { SupplierId = 1, Name = "AK Singh", Address = "Delhi" };

            paramList.Add(product);
            paramList.Add(supplier);

            HttpResponseMessage response = client.PostAsJsonAsync("api/product/SupplierAndProduct", paramList).Result;
            if (response.IsSuccessStatusCode)
            {
                return View();
            }
            else
            {
                return RedirectToAction("About");
            }
        }
        public ActionResult About()
        {
            return View();
        }
}
Now, on Web API controller side, you will get your complex types as shown below.

Now deserialize your complex types one by one from ArrayList as given below-
public class ProductController : ApiController
{
[ActionName("SupplierAndProduct")]
       [HttpPost]
       public HttpResponseMessage SuppProduct(ArrayList paramList)
       {
                if (paramList.Count > 0)
                {
                    Product product = Newtonsoft.Json.JsonConvert.DeserializeObject(paramList[0].ToString());
                    Supplier supplier = Newtonsoft.Json.JsonConvert.DeserializeObject(paramList[1].ToString());

                    //TO DO: Your implementation code

                    HttpResponseMessage response = new HttpResponseMessage { StatusCode = HttpStatusCode.Created };
                    return response;
                }
                else
                {
                    HttpResponseMessage response = new HttpResponseMessage { StatusCode = HttpStatusCode.InternalServerError };
                    return response;
                }
}
}

Method 2: Using Newtonsoft JArray
For passing multiple complex types to your Web API controller, you can also add your complex types to JArray and pass it to your Web API actions as given below-
public class HomeController : Controller
{
        public ActionResult Index()
        {
            HttpClient client = new HttpClient();
            Uri baseAddress = new Uri("http://localhost:2939/");
            client.BaseAddress = baseAddress;

            JArray paramList = new JArray();
            Product product = new Product { ProductId = 1, Name = "Book", Price = 500, Category = "Soap" };
            Supplier supplier = new Supplier { SupplierId = 1, Name = "AK Singh", Address = "Delhi" };

            paramList.Add(JsonConvert.SerializeObject(product));
            paramList.Add(JsonConvert.SerializeObject(supplier));

            HttpResponseMessage response = client.PostAsJsonAsync("api/product/SupplierAndProduct", paramList).Result;

            if (response.IsSuccessStatusCode)
            {
                return View();
            }
            else
            {
                return RedirectToAction("About");
            }
        }
        public ActionResult About()
        {
            return View();
        }
}
Note:
Don't forget to add reference of Newtonsoft.Json.dll to your ASP.NET MVC project and WebAPI as well.
Now, on Web API controller side, you will get your complex types within JArray as shown below.
Now deserialize your complex types one by one from JArray as given below-
public class ProductController : ApiController
{
[ActionName("SupplierAndProduct")]
       [HttpPost]
       public HttpResponseMessage SuppProduct(JArray paramList)
       {
                if (paramList.Count > 0)
                {
                    Product product = JsonConvert.DeserializeObject(paramList[0].ToString());
                    Supplier supplier = JsonConvert.DeserializeObject(paramList[1].ToString());

                    //TO DO: Your implementation code

                    HttpResponseMessage response = new HttpResponseMessage { StatusCode = HttpStatusCode.Created };
                    return response;
                }
                else
                {
                    HttpResponseMessage response = new HttpResponseMessage { StatusCode = HttpStatusCode.InternalServerError };
                    return response;
                }
       }
}
In this way, you can easily pass your complex types to your Web API. There are two solutions; there may be another one as well.


No comments:

Post a Comment