Passing multiple complex type parameters to ASP.NET Web API

Passing multiple complex type parameters to ASP.NET Web API

05 Jul 2024
Intermediate
204K Views
9 min read

Passing multiple complex type parameters to ASP.NET Web API: An Overview

Asp.Net Web API introduces a new powerful REST API that can be consumed by a broad range of clients including browsers, mobiles, iPhones, 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 a single complex type as a parameter, which is a crucial concept to understand in ASP.NET Core Training.

Passing multiple complex type parameters to ASP.NET Web API

Multiple complex type arguments can be passed in many methods in the ASP .NET Web API. Complex types are often custom objects or classes defined in your application. To receive data from client requests, these complicated types can be utilized as parameters in Web API activities.

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; }
}

The code defines two classes: Product, which represents items by ID, name, category, & price, and Supplier, which represents suppliers by ID, name, and address.

In your Asp.Net MVC controller, you are calling your Web API and you need to pass both the class 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();
 }
}

This code creates a HomeController that performs two actions: Index, which sends product and supplier data to an API endpoint, and About, which shows a view.

Now, on the Web API controller side, you will get your complex types as shown below.

Web API Controller Side

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;
 }
 }
}

This code creates a ProductController with an API endpoint to collect product and supplier data, but its fundamental functionality is still missing.

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();
 }
}

The Index action of this HomeController produces a product and a supplier, serializes them as JSON, sends them to an API endpoint, and then renders or redirects based on the response.

Note

Don't forget to add a reference of Newtonsoft.Json.dll to your ASP.NET MVC project and WebAPI as well.

Now, on the Web API controller side, you will get your complex types within JArray as shown below.

Web API Controller side with JArrays

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;
 }
 }
}

This ProductController's API endpoint receives a JSON array of product and supplier data and deserializes it, but its fundamental functionality for processing the data remains unfinished.

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.

Read More: Rest API Interview Questions and Answers
Summary

Due to restrictions, passing numerous complicated types to the ASP.NET Web API necessitates workarounds. While direct parameter passing is not allowed, employing ArrayLists or JArrays with JSON serialization in both the client and API ends allows for more flexible data movement. For serialization, remember to include the Newtonsoft.Json reference. Other ways may exist; investigate more possibilities for optimal solutions.

FAQs

Web API normally pulls the value of the complex type from the request body, but we've used the [FromUri] property here. As a result, Web API will now retrieve the value of the Student attributes from the query string rather than the request body.

We'll use the "&" symbol to separate the other fields and value combinations to pass multiple parameters.

To add a parameter to the URL, append a /#/? followed by the parameter name, an equal sign (=), and the parameter value. You can add additional parameters by separating them with an ampersand (&).

Parameters can be used to pass information to methods. Parameters function as variables within the method. They are specified within the brackets after the method name. You can enter as many options as you wish, separated by a comma.

A web API can be self-hosted in your host process. OWIN should be used by new applications to self-host Web API. Use OWIN to Self-Host ASP.NET Web API 2 for further information.
Share Article
About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

Shailendra Chauhan is the Founder and CEO at ScholarHat by DotNetTricks which is a brand when it comes to e-Learning. He provides training and consultation over an array of technologies like Cloud, .NET, Angular, React, Node, Microservices, Containers and Mobile Apps development. He has been awarded Microsoft MVP 9th time in a row (2016-2024). He has changed many lives with his writings and unique training programs. He has a number of most sought-after books to his name which has helped job aspirants in cracking tough interviews with ease.
Accept cookies & close this