Ashish Chandra
Ashish Chandra

Reputation: 381

Passing JSON Data to REST POST method

I am trying to pass JSON data (present in file) to JSON POST method.

But getting HTTP 400 error (Bad Request) - "The remote server returned an error: (400) Bad Request."

Please help.

Interface -:

[OperationContract]
[WebInvoke(UriTemplate = "/JSON", Method = "POST")]
string CreatePersonFromJSONString(Person createPerson);

Implemented Function -:

 public string CreatePersonFromJSONString(Person createPerson)
  {
     createPerson.ID = (++personCount).ToString();
     persons.Add(createPerson);
     return new JavaScriptSerializer().Serialize(createPerson);
  }

Program -:

 HttpWebRequest req = WebRequest.Create(uri) as HttpWebRequest;
 req.KeepAlive = false;
 req.Method = Method.ToUpper();

if (("POST,PUT").Split(',').Contains(Method.ToUpper()))
 {
   Console.WriteLine("Enter JSON FilePath:");
   string FilePath = Console.ReadLine();
   content = (File.OpenText(@FilePath)).ReadToEnd();

    req.ContentType = "application/json;";

    //initiate the request
    JavaScriptSerializer serializer = new JavaScriptSerializer();
    var resToWrite = serializer.Deserialize<Person>(content);
    StreamWriter PostData = new StreamWriter(req.GetRequestStream());
    PostData.Write(resToWrite);
    PostData.Flush();
    PostData.Close();
}

  HttpWebResponse resp = req.GetResponse() as HttpWebResponse;

Input File Content -:

{  "Age":"25",
       "ID":"4",
       "Name":"Ashish" 
    }

Person Class -:

 [DataContract]
    public class Person
    {
        [DataMember]
        public string ID;
        [DataMember]
        public string Name;
        [DataMember]
        public string Age;
    }

Uri - http://localhost:5171/RestService/JSON

Method - POST

Upvotes: 2

Views: 10073

Answers (2)

Ashish Chandra
Ashish Chandra

Reputation: 381

I had to change the writing of data to Request Stream. No need to deserialize the JSON.

Changed program part -:

byte[] buffer = Encoding.ASCII.GetBytes(content);
req.ContentLength = buffer.Length;
Stream PostData = req.GetRequestStream();
PostData.Write(buffer, 0, buffer.Length);
PostData.Close();

Upvotes: 1

Itai Bar-Haim
Itai Bar-Haim

Reputation: 1674

Seems to me your JSON is invalid.

In JSON the property names must be in quotes so:

{
   "Age":"25",
   "ID":"4",
   "Name":"Ashish" 
}

Upvotes: 0

Related Questions