Call POST method RESTful Service using RestSharp in C#

RestSharp dll is a fully loaded class library for the Service calls, it acts as a client for calling services. Internally it handles all the web Request exceptions.

Initially download Restsharp.dll and Add it to the project reference. Call the same dll in your namespace section to access its library. Also add NewtonSoft Json namespace.

In the below example we are passing the CreateRequest object as input, that later converted to Json. Returned string maintains output Json format.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using RestSharp;

namespace ACTService
{
  public class CreateStyle
  {
   public string createStyle(CreateRequest actStyleRequest, string styleCreateUrl)
     {
          var client = new RestClient(styleCreateUrl);
          var request = new RestRequest(Method.POST);
          string jsonRequest = JsonConvert.SerializeObject(actStyleRequest);
          request.AddParameter(
"application/json; charset=utf-8",
jsonRequest,
ParameterType.RequestBody
);
          request.AddBody(jsonRequest);
          var response = client.Execute(request);
          return response.Content.ToString();
       }
   }
}