Creating Web Service That is Accessible in PHP

Introduction

This article shows how to create a web service that returns multiple values from a database. Normally if we are creating a web service for ASP.NET then we generally return a data set with multiple return statements. But what if we need to consume a web service in PHP developed in .Net and using that web service we need to fetch records, it provides a SOAP client error in the PHP end. This is because of a serialization error. Now I will show you how to create a web service that might fetch Employee records or details and we can consume that Web Service in any programing language.

First let's create a database

Here I am using "Test" as the database and assume it has a table called "Employee" that contains basic fields related to employee information such as FirstName, LastName, Email, ContactNo, Address, State, City, and country.

Database Table
Here is an employee table having basic fields where ID is auto incremented.

Now Create a Web Service

Step 1: Open Visual Studio, select website and then select ASP.NET webservice from the template and provide it the name "WebServiceDemo".

Create a Web Service

Now remove all extra predefined code.

remove all extra code

Use the following namespaces:
 
NameSapces
Now define a connection string object as in the following:
 
Connection String object

Create class with data member and property for the number of parameters that you need as in the following:
 
Property

Now create a method that returns List <EmployeeDetails> as in the following:
 
Class with data Member and Property 
 
method
Now do as I do, here I have written a simple SQL query to read data from the Employee table then I have created an object of list<EmployeeDeatils> Plans= new list<EmployeeDeatils>.

Then create an object of SQL data reader class and use the Execute Reader method to execute the query:

SqlDataReader dr=cmd.ExecuteReader();

Now assign values to the property from the data reader as in the following:

while (dr.Read())

{

    var Details = new EmplaoyeeDetails

    {

        ID = Convert.ToString(dr["ID"]),

        FirstName = Convert.ToString(dr["FirstName"]),

        LastName = Convert.ToString(dr["LastName"]),

        Email = Convert.ToString(dr["Email"]),

        Address = Convert.ToString(dr["Address"]),

        Country = Convert.ToString(dr["Country"]),

         State = Convert.ToString(dr["State"]),

         City = Convert.ToString(dr["City"]),

         ContactNo = Convert.ToString(dr["ContactNo"]),

    };
}

Then close the connection and data reader.

And return the variable Plans to the list.

//Close Connection 

dr.Close();

con.Close();

return Plans;

Now you can consume this web service to any programming language, here I have resolved the issue of serialization and it will work properly.

Sorry for my bad English and grammatical mistakes.


Similar Articles