Click here to Skip to main content
15,893,790 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Dear Experts,

I just need one code example for WCF REST service with POST method. I want to create a post method for taking a request parameter in JSON format and doing the service job. I need one sample example of this and one example of how to call this service method by sending request JSON data as parameter. Pls help me on this.

Below i am giving sample code of service as well as client call method. Where is wrong with this code please let me know.
C#
[OperationContract]
    [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Xml, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "CreateInventory/xml/{DatabaseName}")]
    Stream CreateInventory(string DatabaseName, Stream RequestJSONData);


 public Stream CreateInventory(string DatabaseNameWithAccountID, Stream RequestJSONData)
    {
        StreamReader read = new StreamReader(RequestJSONData);
        string RequestJSONFormat = read.ReadToEnd();
        //My Logic starts here
    }

Client Call
-------------------
C#
string RequestJSONFormat = "Some JSON Data";
string requestURL = "ServiceURL";
            string bodyParams = RequestJSONFormat;
            ASCIIEncoding encoding = new ASCIIEncoding();
            HttpWebRequest request = WebRequest.Create(requestURL) as HttpWebRequest;
            request.Method = "POST";
            request.ContentType = "application/json";
            request.Timeout = 600000;
            string authString = string.Format("{0}", RequestJSONFormat);
            authString = Convert.ToBase64String(encoding.GetBytes(authString));
            authString = string.Format("Basic {0}", authString);
            request.CookieContainer = new CookieContainer();
            byte[] dataToSend = encoding.GetBytes(bodyParams);
            request.ContentLength = dataToSend.Length;
            request.Headers.Add("RequestJSONData", authString);
            request.GetRequestStream().Write(dataToSend, 0, dataToSend.Length);
            request.GetRequestStream().Close();
            StreamReader reader = new StreamReader(request.GetResponse().GetResponseStream(), true);
            string response = reader.ReadToEnd().ToString();
Posted
Updated 9-Oct-13 3:59am
v3
Comments
So, what's the issue?
Sunil Kumar Pandab 10-Oct-13 6:59am    
When i calling from client side, its throwing an exception saying "The remote server returned an error: (400) Bad Request."

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900