Reputation: 439
I've seen a few similar questions on here, but none have worked for this particular problem.
I have a WCF Rest web service and its working ok for GET. One method is a POST, and whenever i call it passing the json parameter, the parameter that is passed is null when the method runs on the web server.
Here is the code:
Client Call:
public async Task Test()
{
HttpClient client;
client = new HttpClient();
client.MaxResponseContentBufferSize = 2147483646;
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
ContactParameter cp = new ContactParameter();
cp.ApptDateFrom = DateTime.Now;
cp.ApptDateTo = DateTime.Now.AddDays(1);
cp.Code = "00";
cp.Type = Enums.ContactType.Person;
cp.Status = string.Empty;
string RestUrl = "http://localhost:61919/data.svc/GetBooked";
var uri = new Uri(string.Format(RestUrl, string.Empty));
JsonSerializerSettings microsoftDateFormatSettings = new JsonSerializerSettings
{
DateFormatHandling = DateFormatHandling.MicrosoftDateFormat,
};
//json string = {"Code":"00","ApptDateTo":"2017-11-22T14:02:01.8758558+00:00","ApptDateFrom":"2017-11-21T14:02:01.8718458+00:00","Type":67,"Status":"A"}
var json = JsonConvert.SerializeObject(cp);
var content = new StringContent(json, Encoding.UTF8, "application/json");
var response = await client.PostAsync(uri, content);
}
WCF Web service contract:
[OperationContract]
[WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "GetBooked")]
List<Contact> GetBooked(ContactParameter contactParameter);
Contact Parameter type
namespace CatService.Types
{
[DataContract (Name = "contactParameter")]
public class ContactParameter
{
[DataMember(Name = "Code")]
public string Code { get; set; }
[DataMember(Name = "ApptDateTo")]
public DateTime ApptDateTo { get; set; }
[DataMember(Name = "ApptDateFrom")]
public DateTime ApptDateFrom { get; set; }
[DataMember(Name = "Type")]
public Enums.Enums.Type Type { get; set; }
[DataMember(Name = "Status")]
public string Status { get; set; }
}
}
I've tried changing the WebMessageBodyStyle.Bare, but then i get a StatusCode: 400, ReasonPhrase: 'Bad Request'. If i try a test method which accepts just a string, it works.
Upvotes: 1
Views: 950
Reputation: 439
This was a datetime issue, i didnt implement the answer on a previous post. Basicaly:
JsonSerializerSettings microsoftDateFormatSettings = new JsonSerializerSettings
{
DateFormatHandling = DateFormatHandling.MicrosoftDateFormat,
};
Then when you serialize....
var json = JsonConvert.SerializeObject(jsonString, microsoftDateFormatSettings);
Upvotes: 0
Reputation: 58
I also get the same problem. I suggest ,you should try your Post method on another console app. Because of POST method not to be on URL.
Upvotes: 0