Membuat Restservice API Dengan WCF C# dan MYSQL


Pada post kali ini saya akan menerangkan bagaimana membuat rest API dengan WCF menggunakan bahasa C# dan database MYSQL

Keuggulan dari rest API ini adalah kita dengan mudah menampilkan hasilnya baik itu berupa JSON maupun XML

Tools dan software yang digunakan
1.     Visual Studio 2017
2.     XAMPP

Buat project “WCF Service Application” baru




 Jika benar maka anda akan mendapatkan file – file ini pada solution explorer anda

 

Buka file “Web.config” dan replace script yang terdapat pada file

 

 dengan script berikut :

 <system.serviceModel>  
 <services>  
 <service behaviorConfiguration="WcfREstService.Service1Behavior" name="RestService.Service1">  
 <endpoint address="" binding="wsHttpBinding" contract="RestService.IService1">  
 <identity>  
 <dns value="localhost" />  
 </identity>  
 </endpoint>  
 <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />  
 </service>  
 <service behaviorConfiguration="ServiceBehaviour" name="WcfREstService.Service1">  
 <endpoint address="" binding="webHttpBinding" contract="WcfREstService.IService1" behaviorConfiguration="web">  
 <!--<identity>  
 <dns value="localhost"/>  
 </identity>-->  
 </endpoint>  
 <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />  
 </service>  
 </services>  
 <behaviors>  
 <serviceBehaviors>  
 <behavior name="WcfREstService.Service1Behavior">  
 <serviceMetadata httpGetEnabled="true" />  
 <serviceDebug includeExceptionDetailInFaults="false" />  
 </behavior>  
 <behavior name="ServiceBehaviour">  
 <serviceMetadata httpGetEnabled="true" />  
 <serviceDebug includeExceptionDetailInFaults="false" />  
 </behavior>  
 </serviceBehaviors>  
 <endpointBehaviors>  
 <behavior name="web">  
 <webHttp />  
 </behavior>  
 </endpointBehaviors>  
 </behaviors>  
 </system.serviceModel>  

Sesuaikan nama script dengan nama file yang terdapat di solution explorer anda

 

Membangun WCF Service

NameSpace

IService1.cs

using System.IO;
using System.ServiceModel;
using System.ServiceModel.Web;

Service1.svc.cs

using System.Collections.Generic;
using System.Data;
using System.IO;
using System.ServiceModel.Web;
using System.Text;
using MySql.Data.MySqlClient;
using Newtonsoft.Json;


Untuk nameSpace Mysql.data.mysqlclient dan Newtonsoft.Json anda perlu menambahkan references baru menggunakan “Manage Nuget Package




 

IService1.cs


 using System.IO;  
 using System.ServiceModel;  
 using System.ServiceModel.Web;  
 namespace WcfREstService  
 {  
   // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together.  
   [ServiceContract]  
   public interface IService1  
   {  
     // TODO: Add your service operations here  
     [OperationContract]  
     [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, UriTemplate = "Getdata")]  
     Stream Getdata();  
   }  
 }  



Service1.svc.cs


 using System.Collections.Generic;  
 using System.Data;  
 using System.IO;  
 using System.ServiceModel.Web;  
 using System.Text;  
 using MySql.Data.MySqlClient;  
 using Newtonsoft.Json;  
 namespace WcfREstService  
 {  
   // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.  
   // NOTE: In order to launch WCF Test Client for testing this service, please select Service1.svc or Service1.svc.cs at the Solution Explorer and start debugging.  
   public class Service1 : IService1  
   {  
     public Stream Getdata()  
     {  
       string jsonstring = "";  
       List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();  
       Dictionary<string, object> row;  
       DataTable dt = new DataTable();  
       string connetionString = null;  
       MySqlConnection cnn;  
       connetionString = "server=localhost;database=[nama_db_anda];uid=root;pwd=;";  
       cnn = new MySqlConnection(connetionString);  
       try  
       {  
         MySqlCommand cm = new MySqlCommand("select * from [nama_table]", cnn);  
         cnn.Open();  
         MySqlDataReader rd = cm.ExecuteReader();  
         dt.Load(rd);  
         cnn.Close();  
         foreach (DataRow dr in dt.Rows)  
         {  
           row = new Dictionary<string, object>();  
           foreach (DataColumn col in dt.Columns)  
           {  
             row.Add(col.ColumnName, dr[col].ToString().Trim());  
           }  
           rows.Add(row);  
         }  
         jsonstring = JsonConvert.SerializeObject(dt);  
         WebOperationContext.Current.OutgoingResponse.ContentType =  
     "application/json; charset=utf-8";  
         return new MemoryStream(Encoding.UTF8.GetBytes(jsonstring));  
       }  
       catch (MySqlException sqlex)  
       {  
         //ic.Message = sqlex.ToString();  
         if (cnn != null)  
           cnn.Close();  
       }  
       finally  
       {  
         if (cnn != null)  
           cnn.Close();  
       }  
       return new MemoryStream(Encoding.UTF8.GetBytes(jsonstring));  
     }  
   }  
 }  


Debug Project dari file Iservice1.cs



Referensi :





Load comments