Rest API C# Console Application

Introduction 

 
This article is about how to create a Rest API C# console application? Before that, we must know what is a RESTful api. A RESTful API is an application program interface (API) that uses HTTP method requests to GET, PUT, POST and DELETE data.
 
A RESTful API, also referred to as a RESTful web service, is based on representational state transfer (REST) technology, an architectural style and approach to communications often used in web services development.
 
The REST technology is generally preferred for the more robust Simple Object Access Protocol (SOAP) technology because the REST leverages less bandwidth, making it  more suitable for internet usage. An API for a website is code that allows two software programs to communicate with each another. The API spells out the proper way for a developer to write a program requesting services from an operating system or other application.
 
The REST usually used by browsers can be thought of as the language of the internet. With cloud use on the rise, APIs are emerging to expose web services. The REST is a logical choice for building APIs that allow users to connect and interact with cloud services. RESTful APIs are used by such sites like Amazon, Google, LinkedIn and Twitter.
In this guide, I will tell you how to make Rest API C# Console Application starting from making a project in Microsoft Visual Studio until testing in browser. You can also follow this instructions directly using your computer.
 
Steps 
 
Create a new project console application with Microsoft Visual Studio 2017 or etc. (Example : restservice)

 
Edit the file app.config like below:
  1. <?xml version="1.0" encoding="utf-8"?>      
  2. <configuration>      
  3.       
  4.   <startup>      
  5.     <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />      
  6.   </startup>      
  7.       
  8.   <system.serviceModel>      
  9.     <serviceHostingEnvironment multipleSiteBindingsEnabled="true"/>      
  10.       
  11.     <bindings>      
  12.       <!--<wsHttpBinding>-->      
  13.       <basicHttpBinding>      
  14.         <binding name="basicHttp" openTimeout="00:10:00" closeTimeout="00:10:00" sendTimeout="00:10:00" receiveTimeout="01:00:00" maxBufferPoolSize="2147483647">      
  15.           <security mode="None">      
  16.             <!--<transport clientCredentialType="None" />-->      
  17.           </security>      
  18.           <!--<reliableSession enabled="true" />-->      
  19.         </binding>      
  20.       </basicHttpBinding>      
  21.       <!--</wsHttpBinding>-->      
  22.       
  23.       <webHttpBinding>      
  24.         <binding name="webHttp" openTimeout="00:10:00" closeTimeout="00:10:00" sendTimeout="00:10:00" receiveTimeout="01:00:00" maxBufferPoolSize="2147483647">      
  25.           <security mode="None">      
  26.             <!--<transport clientCredentialType="None" />-->      
  27.           </security>      
  28.         </binding>      
  29.       </webHttpBinding>      
  30.     </bindings>      
  31.       
  32.     <services>      
  33.       
  34.       <service name="restservice.Service">      
  35.         <endpoint address ="rest" binding="webHttpBinding" bindingConfiguration="webHttp" contract="restservice.IService" behaviorConfiguration="web"></endpoint>      
  36.         <host>      
  37.           <baseAddresses>      
  38.             <add baseAddress="http://localhost:8080" />      
  39.           </baseAddresses>      
  40.         </host>      
  41.       </service>      
  42.     </services>      
  43.       
  44.     <behaviors>      
  45.       <serviceBehaviors>      
  46.         <behavior name="mexBehaviour">      
  47.           <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />      
  48.           <!-- rest api-->      
  49.           <serviceDebug includeExceptionDetailInFaults="false"/>      
  50.         </behavior>      
  51.       </serviceBehaviors>      
  52.       
  53.       <endpointBehaviors>      
  54.         <behavior name="web">      
  55.           <webHttp/>      
  56.         </behavior>      
  57.       </endpointBehaviors>      
  58.     </behaviors>      
  59.   </system.serviceModel>      
  60.       
  61.       
  62.   <runtime>      
  63.     <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">      
  64.       <dependentAssembly>      
  65.         <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />      
  66.         <bindingRedirect oldVersion="0.0.0.0-10.0.0.0" newVersion="10.0.0.0" />      
  67.       </dependentAssembly>      
  68.     </assemblyBinding>      
  69.   </runtime>      
  70. </configuration>    
Create IService.cs for the interface class like below:
  1. using System;    
  2. using System.Collections.Generic;    
  3. using System.Linq;    
  4. using System.Runtime.Serialization;    
  5. using System.ServiceModel;    
  6. using System.ServiceModel.Web;    
  7. using System.Text;    
  8.     
  9. namespace restservice    
  10. {    
  11.     [ServiceContract]    
  12.     public interface IService    
  13.     {    
  14.         [OperationContract]    
  15.         [WebInvoke(Method = "GET",    
  16.              ResponseFormat = WebMessageFormat.Json,    
  17.              BodyStyle = WebMessageBodyStyle.Wrapped,    
  18.              UriTemplate = "login/{username}/{password}")]    
  19.         [return: MessageParameter(Name = "Data")]    
  20.         USER DoLogin(string username, string password);    
  21.     }    
  22.     
  23.         
  24.     public class USER    
  25.     {    
  26.         public string username { getset; }    
  27.         public string password { getset; }    
  28.         public string firstname { getset; }    
  29.         public string lastname { getset; }    
  30.     }    
  31. }   

Add a reference if you get any error. You need a reference like shown below:


After that, we need create a function to return the request. We'll create a new file with the name Service.cs, like below:
  1. using System;    
  2. using System.Collections.Generic;    
  3. using System.Linq;    
  4. using System.Text;    
  5. using System.Threading.Tasks;    
  6.     
  7. namespace restservice    
  8. {    
  9.     public class Service : IService    
  10.     {    
  11.         public USER DoLogin(string user, string pass)    
  12.         {    
  13.             try    
  14.             {    
  15.                 USER data = new USER();    
  16.     
  17.                 if (user == "camellabs" && pass == "camellabs")    
  18.                 {    
  19.                     data.username = user;    
  20.                     data.password = pass;    
  21.                     data.firstname = "ecco";    
  22.                     data.lastname = "suprastyo";    
  23.                 }    
  24.     
  25.                 return data;    
  26.             }    
  27.             catch (Exception ex)    
  28.             {    
  29.                 return null;    
  30.             }    
  31.         }    
  32.     }    
  33. }   

The program class is a console app that is the main entry point to start the application. It configures and launches the web API host and web server using an instance of WebHostBuilder. Edit the program class as below:
  1. using System;    
  2. using System.Collections.Generic;    
  3. using System.Linq;    
  4. using System.ServiceModel;    
  5. using System.ServiceModel.Description;    
  6. using System.ServiceModel.Web;    
  7. using System.Text;    
  8. using System.Threading.Tasks;    
  9.     
  10. namespace restservice    
  11. {    
  12.     class Program    
  13.     {    
  14.         static void Main(string[] args)    
  15.         {    
  16.             WebServiceHost hostWeb = new WebServiceHost(typeof(restservice.Service));    
  17.             ServiceEndpoint ep = hostWeb.AddServiceEndpoint(typeof(restservice.IService), new WebHttpBinding(), "");    
  18.             ServiceDebugBehavior stp = hostWeb.Description.Behaviors.Find<ServiceDebugBehavior>();    
  19.             stp.HttpHelpPageEnabled = false;    
  20.             hostWeb.Open();    
  21.     
  22.             Console.WriteLine("Service Host started @ " + DateTime.Now.ToString());    
  23.     
  24.             Console.Read();    
  25.         }    
  26.     }    
  27. }    
Running the application with Debug or Release mode in Microsoft Visual Studio 2017.
 
Testing the application if already running in the browser, as shown below:
 
You can see the full Rest API C# Console Application Here.
 
Thank you for reading this article on Rest Api Csharp Console Application. I hope this article is useful for you. Visit My Github about .Net & C# Here


Similar Articles