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:
- <?xml version="1.0" encoding="utf-8"?>
- <configuration>
-
- <startup>
- <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
- </startup>
-
- <system.serviceModel>
- <serviceHostingEnvironment multipleSiteBindingsEnabled="true"/>
-
- <bindings>
- <!--<wsHttpBinding>-->
- <basicHttpBinding>
- <binding name="basicHttp" openTimeout="00:10:00" closeTimeout="00:10:00" sendTimeout="00:10:00" receiveTimeout="01:00:00" maxBufferPoolSize="2147483647">
- <security mode="None">
- <!--<transport clientCredentialType="None" />-->
- </security>
- <!--<reliableSession enabled="true" />-->
- </binding>
- </basicHttpBinding>
- <!--</wsHttpBinding>-->
-
- <webHttpBinding>
- <binding name="webHttp" openTimeout="00:10:00" closeTimeout="00:10:00" sendTimeout="00:10:00" receiveTimeout="01:00:00" maxBufferPoolSize="2147483647">
- <security mode="None">
- <!--<transport clientCredentialType="None" />-->
- </security>
- </binding>
- </webHttpBinding>
- </bindings>
-
- <services>
-
- <service name="restservice.Service">
- <endpoint address ="rest" binding="webHttpBinding" bindingConfiguration="webHttp" contract="restservice.IService" behaviorConfiguration="web"></endpoint>
- <host>
- <baseAddresses>
- <add baseAddress="http://localhost:8080" />
- </baseAddresses>
- </host>
- </service>
- </services>
-
- <behaviors>
- <serviceBehaviors>
- <behavior name="mexBehaviour">
- <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
- <!-- rest api-->
- <serviceDebug includeExceptionDetailInFaults="false"/>
- </behavior>
- </serviceBehaviors>
-
- <endpointBehaviors>
- <behavior name="web">
- <webHttp/>
- </behavior>
- </endpointBehaviors>
- </behaviors>
- </system.serviceModel>
-
-
- <runtime>
- <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
- <dependentAssembly>
- <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
- <bindingRedirect oldVersion="0.0.0.0-10.0.0.0" newVersion="10.0.0.0" />
- </dependentAssembly>
- </assemblyBinding>
- </runtime>
- </configuration>
Create IService.cs for the interface class like below:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Runtime.Serialization;
- using System.ServiceModel;
- using System.ServiceModel.Web;
- using System.Text;
-
- namespace restservice
- {
- [ServiceContract]
- public interface IService
- {
- [OperationContract]
- [WebInvoke(Method = "GET",
- ResponseFormat = WebMessageFormat.Json,
- BodyStyle = WebMessageBodyStyle.Wrapped,
- UriTemplate = "login/{username}/{password}")]
- [return: MessageParameter(Name = "Data")]
- USER DoLogin(string username, string password);
- }
-
-
- public class USER
- {
- public string username { get; set; }
- public string password { get; set; }
- public string firstname { get; set; }
- public string lastname { get; set; }
- }
- }
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:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
-
- namespace restservice
- {
- public class Service : IService
- {
- public USER DoLogin(string user, string pass)
- {
- try
- {
- USER data = new USER();
-
- if (user == "camellabs" && pass == "camellabs")
- {
- data.username = user;
- data.password = pass;
- data.firstname = "ecco";
- data.lastname = "suprastyo";
- }
-
- return data;
- }
- catch (Exception ex)
- {
- return null;
- }
- }
- }
- }
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:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.ServiceModel;
- using System.ServiceModel.Description;
- using System.ServiceModel.Web;
- using System.Text;
- using System.Threading.Tasks;
-
- namespace restservice
- {
- class Program
- {
- static void Main(string[] args)
- {
- WebServiceHost hostWeb = new WebServiceHost(typeof(restservice.Service));
- ServiceEndpoint ep = hostWeb.AddServiceEndpoint(typeof(restservice.IService), new WebHttpBinding(), "");
- ServiceDebugBehavior stp = hostWeb.Description.Behaviors.Find<ServiceDebugBehavior>();
- stp.HttpHelpPageEnabled = false;
- hostWeb.Open();
-
- Console.WriteLine("Service Host started @ " + DateTime.Now.ToString());
-
- Console.Read();
- }
- }
- }
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.