21
NovPassing multiple complex type parameters to ASP.NET Web API
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.
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.
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.