HI WELCOME TO SIRIS

Ionic 6 Cordova Geolocation and Geocoder Tutorial

Leave a Comment

 Ionic 6 Angular Geolocation and Geocoder tutorial; This is a step by step tutorial on how to use Cordova Geolocation and Geocoder plugin in an Ionic app to get the current user device position, get current user address.

In this tutorial we are going to learn how to get users device location with latitude and longitude.We will learn to get the users address using Geolocation and Geocoder Plugins.

We will look at how to add target platforms such as iOS, Android or Windows and create the build in Ionic for various devices.

Ionic 6 Angular Get Geolocation Example

  • Step 1: Prerequisite
  • Step 2: Create New Ionic Angular Project
  • Step 3: Install & Configure Cordova Geolocation and Geocoder Plugins
  • Step 4: Get Current Location Latitude and Longitude
  • Step 5: Get Current Address
  • Step 6: Start Ionic App

Prerequisite

We must have the latest version of Node js installed on our device. If you are not having then follow this tutorial on: How to Download and Install Node.js and npm

Create New Ionic / Angular Project

Use the command to install Cordova globally on your machine.

sudo npm install -g cordova ionic
Bash

By using the following command, you can check the Ionic CLI version running on your machine.

ionic -v
Bash

Use below command to update Ionic and Cordova.

sudo npm update -g cordova ionic
Bash

Let’s start installing a brand new Ionic Angular app with the help of Ionic CLI, run the following command in your terminal.

ionic start ionic-geolocation-app blank --type=angular
Bash

Get inside the project folder.

cd ionic-geolocation-app
Bash

Start the app in the browser.

ionic serve --lab
Bash

How to Install & Configure Cordova Geolocation, Geocoder and Ionic Native Plugins

In this step, we will first install then configure Cordova Geolocation, Geocoder and Ionic native plugins in an Ionic app.

Geolocation

The cordova-plugin-geolocation plugin API is based on the W3C Geolocation API Specification and helps to get the location (latitude and longitude) data.

This plugin provides information about the device’s location, such as latitude and longitude. Common sources of location information include Global Positioning System (GPS) and location inferred from network signals such as IP address, RFID, WiFi and Bluetooth MAC addresses, and GSM/CDMA cell IDs.

ionic cordova plugin add cordova-plugin-geolocation
Bash

Install @ionic-native/geolocation via npm using the below command.

npm install @ionic-native/geolocation
React JSX

This geo location plugin provides device data such as device location, latitude and longitude. Common sources of location information include Global Positioning System (GPS) and location inferred from network signals such as IP address, RFID, WiFi and Bluetooth MAC addresses, and GSM/CDMA cell IDs.

It supports following platforms:

  • iOS
  • Android
  • Windows
  • Browser
  • Amazon Fire OS

Add given below configuration to your configuration.xml file for iOS support.

<edit-config file="*-Info.plist" mode="merge" target="NSLocationWhenInUseUsageDescription">
   <string>We use your location for full functionality of certain app features.</string>
</edit-config>
React JSX

Native Geocoder

The native geocoder plugin helps us to get the address for given coordinates and also does forward and reverse geocoding for iOS and Android platforms.

ionic cordova plugin add cordova-plugin-nativegeocoder
npm install @ionic-native/native-geocoder
Bash

Import Plugins in Main AppModule

Add the above plugins in the main Ionic app module file, open app.module.ts file, and import and add plugins in an import array.

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouteReuseStrategy } from '@angular/router';
import { IonicModule, IonicRouteStrategy } from '@ionic/angular';
import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';
// geolocation and native-geocoder
import { Geolocation } from '@ionic-native/geolocation/ngx';
import { NativeGeocoder } from '@ionic-native/native-geocoder/ngx';
@NgModule({
  declarations: [AppComponent],
  entryComponents: [],
  imports: [BrowserModule, IonicModule.forRoot(), AppRoutingModule],
  providers: [
    Geolocation,
    NativeGeocoder,
    { 
      provide: RouteReuseStrategy, 
      useClass: IonicRouteStrategy
    }
  ],
  bootstrap: [AppComponent],
})
export class AppModule {}
TypeScript

Get Current User’s Device Location Latitude and Longitude using Geolocation and Native Geocoder Plugin

Apps like Whatsapp, Uber, Ola, and many more depending on the user’s location, and without location, we can’t imagine modern days web and mobile applications. Almost every application uses the location service to offer excellent services to its users.

Finding a geo location with Cordova Geolocation is very easy, and We are going to get the current lat long of the user’s device.

In this step, I am going to describe how to locate the user’s device position, open home.pge.ts file and add the given code in it.

// home.page.ts
import { Component, NgZone } from '@angular/core';
import { Geolocation } from '@ionic-native/geolocation/ngx';
@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage {
  latitude: any = 0; //latitude
  longitude: any = 0; //longitude
  constructor(
    private geolocation: Geolocation
  ) {}
  options = {
    timeout: 10000, 
    enableHighAccuracy: true, 
    maximumAge: 3600
  };
  // use geolocation to get user's device coordinates
  getCurrentCoordinates() {
    this.geolocation.getCurrentPosition().then((resp) => {
      this.latitude = resp.coords.latitude;
      this.longitude = resp.coords.longitude;
     }).catch((error) => {
       console.log('Error getting location', error);
     });
  }
}
TypeScript

To get the geographical position of a user, we imported the Geolocation API at the top, then injected in the constructor and accessed the getCurrentPosition() method to get the user’s position.

The getCurrentPosition() method returns geolocation data which contains a timestamp, GeoLocation coordinates such as latitude, longitude, altitude, accuracy, alititudeAccuracy, heading and speed.

The getCurrentPosition() function takes 3 parameters, success, error and options. In the options we specify timeout, enableHighAccuracy and maximumAge.

Add the following code in home.page.html file.

// home.page.html
<ion-header>
  <ion-toolbar>
    <ion-title>
        Ionic Geolocation & Geocoder Examples
    </ion-title>
  </ion-toolbar>
</ion-header>
<ion-content>
  <div class="ion-padding">
    <ion-button (click)="getCurrentCoordinates()" expand="block">
      Get Location
    </ion-button>
  <ion-list>
    <ion-list-header>
      <ion-label>Location Coordinates</ion-label>
    </ion-list-header>
    <ion-item>
      <ion-label>
        Latitue
      </ion-label>
      <ion-badge color="danger" slot="end">{{latitude}}</ion-badge>
    </ion-item>
    <ion-item>
      <ion-label>
        Longitude
      </ion-label>
      <ion-badge color="danger" slot="end">{{longitude}}</ion-badge>
    </ion-item>
    </ion-list>    
  </div>
</ion-content>
Markup

Get Current User's Device Location Latitude and Longitude using Geolocation and Native Geocoder Plugin

Getting Current Address

To get the current address of the location. We need to import the following services at the header part of the Ionic TypeScript template.

import { NativeGeocoder, NativeGeocoderResult, NativeGeocoderOptions } from '@ionic-native/native-geocoder/ngx';
TypeScript

Open the home.page.ts file then add the following code.

import { Component, NgZone } from '@angular/core';
import { Geolocation } from '@ionic-native/geolocation/ngx';
import { NativeGeocoder, NativeGeocoderResult, NativeGeocoderOptions } from '@ionic-native/native-geocoder/ngx';
@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage {
  latitude: any = 0; //latitude
  longitude: any = 0; //longitude
  address: string;
  constructor(
    private geolocation: Geolocation,
    private nativeGeocoder: NativeGeocoder
  ) {}
  // geolocation options
  options = {
    timeout: 10000, 
    enableHighAccuracy: true, 
    maximumAge: 3600
  };
  // use geolocation to get user's device coordinates
  getCurrentCoordinates() {
    this.geolocation.getCurrentPosition().then((resp) => {
      console.log(resp)
      this.latitude = resp.coords.latitude;
      this.longitude = resp.coords.longitude;
      this.getAddress(this.latitude, this.longitude);
     }).catch((error) => {
       console.log('Error getting location', error);
     });
  }
  // geocoder options
  nativeGeocoderOptions: NativeGeocoderOptions = {
    useLocale: true,
    maxResults: 5
  };
  // get address using coordinates
  getAddress(lat,long){
    this.nativeGeocoder.reverseGeocode(lat, long, this.nativeGeocoderOptions)
    .then((res: NativeGeocoderResult[]) => {
      this.address = this.pretifyAddress(res[0]);
    })
    .catch((error: any) => {
      alert('Error getting location'+ JSON.stringify(error));
    });
  }
  // address
  pretifyAddress(address){
    let obj = [];
    let data = "";
    for (let key in address) {
      obj.push(address[key]);
    }
    obj.reverse();
    for (let val in obj) {
      if(obj[val].length)
      data += obj[val]+', ';
    }
    return address.slice(0, -2);
  }
}
TypeScript

We defined address variable, then injected the NativeGeocoder API in the constructor.

The getAddress() method takes lat and long parameter, inside the function the reverseGeocode API provides reverseGeocode method that takes lat, long and nativeGeocoderOptions parameters and returns the address array. That raw address data is being filtered by pretifyAddress() method and returning comma separated address.

Start Ionic App in Device

We will learn how to add target platforms for iOS, Android and Windows to test our app.

# iOS
ionic cordova platform add ios
# Android
ionic cordova platform add android
# Windows
ionic cordova platform add windows
Bash

Use the following commands to build your Ionic app for various platforms:

# iOS
ionic cordova build ios
# Android
ionic cordova build android
# Windows
ionic cordova build windows
Bash

Start the app in the device.

# iOS
ionic cordova run ios -l
# Android
ionic cordova run android -l
# Windows
ionic cordova run windows -l
Bash

Conclusion

Finally, Ionic Cordova Geolocation and Geocoder plugins tutorial has been over. In this tutorial we have learned how to:

  • Set up a basic Ionic app from scratch.
  • Install and configure Cordova Geolocation and Geocoder Plugins in Ionic app.
  • Locate Current Location Latitude and Longitude.
  • Get Current User Address.
  • Add Target Platforms.
  • Build Ionic App.

Content Negotiation in ASP.NET WebAPI

Leave a Comment

 As the name suggest, Web API, an Application Programming Interface for Web. In other words, it’s a framework which is used to create services aka API’s which can be consumed by clients using browser or tablets or mobile devices. Basically, it is used to create RESTful services. To find more over REST, have a look into Difference between SOAP And REST APIs. Whenever we consume an API, we receive data in either JSON or XML or plain text or your own custom format. I.e. the requester and responder are aware of the format in which they will receive data. This is nothing but Content Negotiation in Web API 2.

How Content Negotiation Works

There are two main headers which hold the responsibility of content negotiation

  • Content-Type

  • Accept

Let’s try to understand them. When a requester send a service request, the CONTENT-TYPE tells responder the format he will receive data whereas the ACCEPT header tells in which format the requester requires the data.

Default Content Negotiator

In the above pictorial view, there are few points which should be noted down,

  • User 2 didn’t mention Content-Type but then received the response in desired format. I.e. XML.

  • Whereas User 4 didn’t mention both Content-Type as well as Accept header. But then received the response. I.e. in JSON format. In short, JSON format is the default content negotiator in web api 2.

  • Also, User 3 requires data in text/html format but receives data in XML format. In short, text/html Accept header sends response in XML format by default.

    Till now, we had lots of theory. Let’s see the above pictorial view in .Net platform.

Creating Web API Application in .NET

Let’s create a Web API 2 application for understanding Content Negotiation. I will be creating the project using.

  • Visual Studio 2017

  • Entity Framework 6

  • SQL Server 2012 – I have used Adventure Works sample Database – Go through https://www.tutorialgateway.org/download-and-install-adventureworks-database/ to download and bind the SQL database

To create the application follow the below steps,

  1. In Visual Studio 2017, select File > New>Project> Asp.Net Web Application (.Net Framework)

  2. Choose the desired path, project name and .Net Framework 4.6.1. As a FYI, .Net Framework 4.5 and above supports Web API2 features. Click OK

  3. In this step, you will get the list of templates supported by .Net framework 4.6.1. For this tutorial, I am selecting Web API. Please note, the MVC and Web API checkboxes are checked by default. Click ok.

  4. In few minutes, your Web API project will be created with a default project structure and a controller to begin with.

  5. Now let us bind our Adventure works database. I will be using Entity Framework Database first approach. For this, right-click on your Models folder> Add > New Item> ADO.Net Entity Data Model. Give name to your .edmx file and click Add.

  6. Now select EF Designer from database. Click Next > Select the connection string if existing else click on New connection & create the connection string. Once done click ok and then next.

  7. Here in visual studio 2017, you get an option to select version of EF. I will be selecting Entity Framework 6.x. Click Next

  8. Select the desired Tables, View or Store procedure. I will go ahead only with Product Table. Click Finish. In sometime, your .edmx file will be created with Product Entity.

  9. Now let’s create a web api Products Controller. Right-click on Controllers folder > Add> New Scaffolder item > Web API 2 with actions using Entity Framework > Click Add.

  10. Select the desired Model class, DataContext class and Controller name > Click Add. A controller with pre-written Actions will be created.

  11. Run the application and in your browser, write api/Products after the localhost. You will get your data in XML Format.

Downloading and Installing Postman

For testing the Web API, you can either use fiddler or postman. Here I will be using Postman. You can download and install the same from,https://www.getpostman.com/appsLet’s check if the application is running in POSTMAN. Copy the URL from browser and paste it beside the GET button and click SEND. You will receive the desired data long with repose status code.

Great!! Your application worked!! So now we are ready to deep-dive into understanding Content Negotiation with examples. If you don’t wish to download the POSTMAN application, then chrome provides an add-in for the same. https://chrome.google.com/webstore/detail/postman/fhbjgbiflinjbdggehcddcbncdddomop?hl=enI personally prefer using the application so I have downloaded and installed it.

OVERVIEW OF POSTMAN

After building a web API or service application, we all would like to test them without consuming it. For such purpose, Fiddler and Postman are being used. I will go ahead and give small overview about Postman before testing our application. Postman provides a wide range of features for our use. It has made a developer life quite easy. One of them is we can easily create an account in Postman so that if in case we want to save our test cases for future use. What a relief!!

Above fig is the landing page of postman application. It’s basically divided into 3 portions,

  • Request Panel : where you note down the details you wish to send to the server.

  • Response Panel : where you can see the data you requested for.

  • History Panel : this will list down the entire service request you made each day.

    You can go through https://www.youtube.com/watch?v=FjgYtQK_zLE to understand more functionality postman offers. Now let us see how we can request the service and how we receive response from the server.

Testing Content Negotiation or WebApi with Postman

As we all know, there are 4 types of operation or HTTP verbs we can perform,

  1. GET

  2. PUT

  3. POST

  4. DELETE

I will be explaining them one by one. Let’s get started!!

GET REQUEST

This request is used when we simply want to receive data from server. So for me, I need a list of all the products.

Test Case 1

As we didn’t specify the ACCEPT header, the server gave us back JSON data, which is the default content-type for a response. Let us specify the ACCEPT header. For this,

  • Click on headers tab in request panel

  • Enter ACCEPT under key in first row and value as application/XML.

  • Click Send

    Now we get the response body as XML. Similarly we can request data in other formats like text, json, xml and so on.

Test Case 2

Now if we want to send a parameter along with the GET method, there are two ways,

  • Send the product id value with the URL. For example, http://localhost:1240/api/Products/4

  • Set a parameter and make a call to http://localhost:1240/api/Products

    We will try the second option. For this,

  • click on the Params button beside the send button

  • Enter id as key and 4 as value

  • Specify the Accept header if any and click send

Note that whatever request we are making, it’s getting saved in the History panel. We can anytime double click on the desired URL and check our past test case result.

PUT Method

If we want to update any existing data, we use the PUT method.

Test case 3
  • click on the Params button beside the send button

  • Enter id as key and 4 as value

  • Now as we need to send the data which we need to update, we have to tell server what is the format of the input data. So we specify Content-Type.

  • Specify the Accept header if any

  • Change the HTTP verb to PUT

  • In body tab, enter the JSON input data and click send

    Ooopzz!! We receive no data in our response panel with a status of ‘ 204 No Content’.

    So isn’t our data updated? To check if our data is updated, repeat Test case 2. You can see the changes. But we would like to get the data back immediately after hitting the URL instead of repeating the Testcase 2. For this, we need to update few small line in our PUT action method.

  • Replace

     
     [ResponseType(typeof(void))] with [ResponseType(typeof(Product))]
    
  • Replace

     
     return StatusCode(HttpStatusCode.NoContent); with 
     Product product1 = db.Products.Find(id);
     return Ok(product1);
    

    Save and Run your application. Repeat Test Case 4. In PUT as well, we can shuffle around content-type and Accept headers as per our need.

POST Method

Is use to create new data in database. Steps to create the scenario are similar to Testcase 3. Only difference, we are not supposed to send any Id as input.

Test Case 4
  • As we need to send the data which we need to update, we have to tell server what is the format of the input data. So we specify Content-Type.

  • Specify the Accept header if any

  • Change the HTTP verb to POST

  • In body tab, enter the JSON input data and click send

A new product with ProductId = 1001 has been created. To test, we can repeat TestCase 2 and check.

DELETE Method

As the name says, use to delete an existing data.

Test case 5
  • click on the Params button beside the send button

  • Enter id as key and 1001 as value

  • Now as we need to send the data which we need to update, we have to tell server what is the format of the input data. So we specify Content-Type.

  • Specify the Accept header if any

  • Change the HTTP verb to DELETE

  • Click Send.

    As a response we get back the Product details which we delete. So repeat TestCase 2 and now we see no data with a status code ‘Not Found’.

Bounding WebAPI to send only json or xml formatted data

Now there are cases where we want our application to receive only JSON or XML formatted data irrespective of the ACCEPT header value. To achieve this, add a below line in App_Start > WebApiConfig.cs> Register method.

config.Formatters.Remove(config.Formatters.XmlFormatter);

This will remove the XML formatter and always return JSON data. I executed TestCase 1 with Accept header as application/xml.

Similarly to get data in only XML format, below is the code.

config.Formatters.Remove(config.Formatters.JsonFormatter);

Returning data based upon the accept header

For this purpose, add the below line of code in App_Start> WebApiConfig.cs> Register method

config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new System.Net.Http.Headers.MediaTypeHeaderValue("text/html"));
Summary

Content-Type and Accept header are the important elements while requesting a service. It tells the service in which format he will be receiving the input and in which format he needs to send the data back respectively. If you are making an Ajax call, below is the basic structure

$.ajax({
 url: "http://localhost:1240/api/Products",
 dataType: "application/xml",
 contentType: "application/json; charset=utf-8",
 data: JSON.stringify(inputdata),
 success: function(result) { },
});

Where, dataType is the ACCEPT header value. Data is the input data you sending to the server.

Comparing Asp.Net Web API Routing and Asp.Net MVC Routing

Leave a Comment

 As you know, Routing is a pattern matching system that monitor the incoming request and figure out what to do with that request. A URL pattern is matched against the routes patterns defined in the Route dictionary in an Order and the first match wins. This means the first route which successfully matches a controller, action, and action parameters defined in the URL will call into the specified controller and action.

Asp.Net MVC application and Asp.Net Web API must have at least one route defined in order to function. Hence, Visual Studio templates defined for MVC and Web API must have a default route. Now let's understand the difference between Asp.Net MVC and Asp.Net Web API.

Default Route Pattern

The default route pattern for a Web API Project is defined as follows-

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

The literal api at the beginning of the Web API route pattern, makes it distinct from the standard MVC route. This is not mandatory but it is a good convention to differ Web API route from MVC route.

In Web API route pattern {action} parameter is optional but you can include an {action} parameter. Also, the action methods defined on the controller must be have an HTTP action verb as a prefix to the method name in order to work. So, you can also define the route for Web API as follows-

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

The default route pattern for an Asp.Net MVC Project is defined as follows-

routes.MapRoute(
 name: "Default", //route name
 url: "{controller}/{action}/{id}", //route pattern
 defaults: new 
 { 
 controller = "Home", 
 action = "Index", 
 id = UrlParameter.Optional
 } //parameter default values
 );

As you have seen there is no literal before at the beginning of the Asp.Net MVC route pattern but you can add if you wish.

Route Processing

In Web API route processing the URLs map to a controller, and then to the action which matches the HTTP verb of the request and the most parameters of the request is selected. The Action methods defined in the API controller must either have the HTTP action verbs (GET, POST, PUT, DELETE) or have one of the HTTP action verbs as a prefix for the Actions methods name as given below-

public class ValuesController : ApiController
{
 // GET api/
 public IEnumerable Get()
 {
 return new string[] { "value1", "value2" };
 }

 // GET api//5
 public string Get(int id)
 {
 return "value";
 }

 // POST api/
 public void Post([FromBody]string value)
 {
 }

 // PUT api//5
 public void Put(int id, [FromBody]string value)
 {
 }

 // DELETE api//5
 public void Delete(int id)
 {
 }
} 

// OR You can also defined above API Controller as Verb Prefix

public class ValuesController : ApiController
{
 // GET api/values
 public IEnumerable GetValues()
 {
 return new string[] { "value1", "value2" };
 }
 // GET api/values/5
 public string GetValues(int id)
 {
 return "value";
 }
 // POST api/values
 public void PostValues([FromBody]string value)
 {
 }
 // PUT api/values/5
 public void PutValues(int id, [FromBody]string value)
 {
 }
 // DELETE api/values/5
 public void DeleteValues(int id)
 {
 }
}

In Asp.Net MVC route processing the URLs map to a controller, and then to the action which matches the HTTP verb of the request and the most parameters of the request is selected. The Action methods defined in the MVC controller do not have HTTP action verbs as a prefix for the Actions methods but they have name like as normal method as shown below-

public class HomeController : Controller
{
 // GET: /Home/Index
 public ActionResult Index() //method - Index
 {
 // To Do:
 return View();
 }

 // Post: /Home/Index
 [HttpPost]
 public ActionResult Index(LoginModel model, string id)
 {
 // To Do:
 return View();
 }
} 

In MVC, by default HTTP verb is GET for using others HTTP verbs you need defined as an attribute but in Web API you need to define as an method's name prefix.

Complex Parameter Processing

Unlike MVC, URLs in Web API cannot contain complex types. Complex types must be placed in the HTTP message body and there should be only one complex type in the body of an HTTP message.

Base Library

Web API controllers inherit from, but MVC controllers inherit from System.Web.Mvc.Controller. Both the library are different but acts in similar fashion.

What do you think?

I hope you will enjoy the tips while programming with Asp.Net MVC and Web API. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.

Passing multiple complex type parameters to ASP.NET Web API

Leave a Comment

 Asp.Net Web API introduces a new powerful REST API which can be consume 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 solution, there may be another one as well.

What do you think?

I hope you will enjoy the tips while programming with Asp.Net Web API. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.