duncanportelli
duncanportelli

Reputation: 3219

WCF RESTful Service - HTTP POST Request

I developed a WCF Service with the following post method:

[OperationContract]
[WebInvoke(Method = "POST",
    ResponseFormat = WebMessageFormat.Json,
    BodyStyle = WebMessageBodyStyle.Wrapped,
    UriTemplate = "/InsertBearingData")]
bool InsertBearingData(String JSONString);

I am using Fiddler to formulate an HTTP POST Request for this method but, it is returning Status Code - 400 Bad Request. This is the request formulated:

Request Header:

Host: localhost:21468
Content-Length: 96
Content-Type: application/json

Request Body:

[{"start time":"29-03-2013 11:20:11.340","direction":"SW","end time":"29-03-2013 11:20:14.770"}]

Can you please tell me how to formulate a good request in order to get a succesful response?

Upvotes: 3

Views: 2319

Answers (1)

carlosfigueira
carlosfigueira

Reputation: 87218

There are a few issues in your code:

  • The data type of the parameter is string, but you're passing a JSON array to it; a string parameter requires a JSON string to be passed.
  • The body style of the operation is set to Wrapped, which means that the parameter should be wrapped in an object whose key is the parameter name, something like {"JSONString":<the actual parameter value>}

To receive a request like the one you're sending, you need to have an operation like the following:

[ServiceContract]
public interface ITest
{
    [WebInvoke(Method = "POST",
        ResponseFormat = WebMessageFormat.Json,
        BodyStyle = WebMessageBodyStyle.Bare,
        UriTemplate = "/InsertBearingData")]
    bool InsertBearingData(MyType[] param);
}

[DataContract]
public class MyType
{
    [DataMember(Name = "start time")]
    public string StartTime { get; set; }
    [DataMember(Name = "end time")]
    public string EndTime { get; set; }
    [DataMember(Name = "direction")]
    public string Direction { get; set; }
}

Upvotes: 3

Related Questions