How to send request from CURL command tool to WCF REST service

This post will show you how to test your rest service from the command prompt using the CURL tool.

What is CURL: A command-line tool for getting or sending files using URL syntax.

For this demo, I have created a simple reset service that contains three methods as below

Download Source Code
[ICurlService]

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;


[ServiceContract(SessionMode = SessionMode.NotAllowed)]
public interface ICurlService
{
    [WebGet(UriTemplate = "date/{year}/{month}/{day}", ResponseFormat = WebMessageFormat.Xml)]
    [OperationContract]
    string GetDate(string day, string month, string year);

    [WebGet(UriTemplate = "greet", ResponseFormat = WebMessageFormat.Json)]
    [OperationContract]
    string Greeting();

    [WebInvoke(Method = "POST", UriTemplate = "submit", BodyStyle = WebMessageBodyStyle.WrappedRequest, ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
    [OperationContract]
    string Save(string data);

}

[ServiceType]

using System;

using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

public class ServiceType : ICurlService
{
    public string GetDate(string day, string month, string year)
    {
        return new DateTime(Convert.ToInt32(year), Convert.ToInt32(month), Convert.ToInt32(day)).ToString("dddd, MMMM dd, yyyy");
    }
   public string Greeting()
    {
        return "Hello World";
    }
   public string Save(string data)
   {
       return data + "Has been saved!";
   }
}

Let’s send the request to the first method

[WebGet(UriTemplate = "date/{year}/{month}/{day}", ResponseFormat = WebMessageFormat.Xml)]
  [OperationContract]
  string GetDate(string day, string month, string year);

Go to command prompt and type the following code

curl http://localhost:12576/CurlDemo/Service.svc/date/2012/1/12** 

Let’s send the request to the second method from curl.


  [WebGet(UriTemplate = "greet", ResponseFormat = WebMessageFormat.Json)]
    [OperationContract]
    string Greeting();
curl http://localhost:12576/CurlDemo/Service.svc/greet

Now, let’s send a post request to service from the command prompt.

[WebInvoke(Method =  "POST", UriTemplate =  "submit", BodyStyle = WebMessageBodyStyle.WrappedRequest, ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]

[OperationContract]

string  Save(string  data);

curl -H "Content-Type: application/json" -H "Accept: application/json" -X POST -d '{"data":"dummy data"}' http://localhost:12576/CurlDemo/Service.svc/submit

Post a Comment

Please do not post any spam link in the comment box😊

Previous Post Next Post

Blog ads

CodeGuru