简体   繁体   中英

C# RestSharp POST Body using models

I'm just starting out with RestSharp using C#.

I encountered an error while doing the following scenario.

I have a class that I want to post to my WCF service via RestSharp. However, I found out that the date time property is causing the request fail to post.

This is the error message return from Rest Sharp.

The server encountered an error processing the request. See server logs for more details.

/*Model to POST to WCF*/
public class Ticket {
  public string Name {get;set;}
  public DateTime Time {get;set;}
}

/*WCF Api Endpoint*/
[OperationContract, WebInvoke(UriTemplate = "/placeTicket", Method 
= "POST", BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = 
WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
NewTicket MakeNewTicket(Ticket requestParams);

/*Rest Sharp Operation*/
Ticket model = new Ticket();
model.Name = "Danial";
model.Time = new DateTime();

var client = new RestClient(url);
var request = new RestRequest("/MakeNewTicket", Method.POST);
request.RequestFormat = DataFormat.Json;
request.AddBody(model);

If i change the Time property to string, it works perfectly.

I've been stretching my head trying to solve this problem. Anyone able to guide me on this will be appreciated.

I found a solution. I need to serialize the model object sent to WCF service using microsoft date format handling.

var client = new RestClient(url);
var request = new RestRequest("/placeTicket", Method.POST);
request.RequestFormat = DataFormat.Json;
var requestModel = JsonConvert.SerializeObject(model, new 
JsonSerializerSettings { DateFormatHandling = 
DateFormatHandling.MicrosoftDateFormat } )
request.AddBody(model);
var responseData = client.Execute(request).Content;

I'm not sure why when passing pure model using the date format standard of ISO 8601 not able to fire to my WCF service. However if I'm using Microsoft JSON date format setting. It works fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM