WCF REST SERVICE POST JSON OBJECT

Prabhat39
Posted by Prabhat39 under C# category on | Points: 40 | Views : 1703
In this method formdata is nothing but the object passed to the server from client and serviceUrl is the rest address where wcf service is hosted. You have to use Microsoft.Http dll.

   
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.Serialization.Json;
using System.Web;
using Microsoft.Http;

public object GetRequestRESTService(Dictionary<string, string> formData, string serviceUrl)
{
string jsonData = string.Empty;
var host = HttpContext.Current.Request.Url.Authority;
var restServiceBridgeUrl = string.Format("http://{0}/", host);
using (var client = new HttpClient(restServiceBridgeUrl))
{
var content = HttpContentExtensions.CreateJsonDataContract(formData);
ExtendTimeout(client);
try
{
using (HttpResponseMessage response = client.Post(serviceUrl, content))
{
jsonData = response.Content.ReadAsJsonDataContract<string>();
}
}
catch (Exception ex)
{
jsonData = " " + ex.ToString();
}
}
return jsonData;
}

[Conditional("DEBUG")]
private static void ExtendTimeout(HttpClient client)
{
client.TransportSettings.ConnectionTimeout = new TimeSpan(0, 5, 0);//5 minutes
}

Comments or Responses

Login to post response