我希望有人可以帮助我。我有一个WCF REST服务,它可以正常使用所有GET功能。但是我无法使POST方法起作用。我的服务合同是
[OperationContract]
[WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Wrapped, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, UriTemplate = "NewEmployeeLeave/")]
string addTimeOff(mmpTimeOff data);
正在调用以下
// addTimeOff
// Add a new time off record with passed information
public string addTimeOff(mmpTimeOff data)
{
try
{
// Add the new record to the employees leave requests
mmpTimeOff newTimeOff = data;
db.TimeOffs.Add(new TimeOff
{
StartDate = newTimeOff.StartDate,
EndDate = newTimeOff.EndDate,
PersonId = newTimeOff.PersonId,
Manager = newTimeOff.Manager,
TimeOffType = newTimeOff.TimeOffType,
Status = newTimeOff.Status,
Notes = newTimeOff.Notes
});
db.SaveChanges();
}
// Make sure that we can push the error back to the client.
catch (Exception e)
{
return e.Message;
}
return "ok";
}
客户端代码如下。
client = new HttpClient();
HttpResponseMessage response=new HttpResponseMessage();
mmpPerson user = new mmpPerson();
client.BaseAddress = new Uri(url);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
try
{
mmpTimeOff newLeave = new mmpTimeOff()
{
PersonId = user.Id,
StartDate = DateTime.Parse("2017-10-22"),
EndDate = DateTime.Parse("2017-10-28"),
TimeOffType = "Annual",
Manager = user.Manager,
Status = "Appr"
};
response = await client.PostAsJsonAsync(url + "/newemployeeleave", newLeave);
if (response.IsSuccessStatusCode)
{
ViewBag.Added = "Added New Leave Successfully";
}
当客户端运行时,我得到一个空值,通过addTimeOff方法发送。
该类在服务中定义为
public class mmpTimeOff
{
[DataMember]
public int Id { get; set; }
[DataMember]
public System.DateTime StartDate { get; set; }
[DataMember]
public System.DateTime EndDate { get; set; }
[DataMember]
public string TimeOffType { get; set; }
[DataMember]
public int PersonId { get; set; }
[DataMember]
public string Status { get; set; }
[DataMember]
public Nullable<int> Manager { get; set; }
[DataMember]
public string Notes { get; set; }
}
并作为连接服务绑定到客户端。
如何成功将对象数据传递到服务。
感谢所有的帮助。
里克
答案 0 :(得分:0)
尤里卡!!!!
感谢尤金。在阅读了你的回复并查看了链接之后,我使用POSTMAN进行了一些进一步的调查,我发现PostAsJsonAsync确实正在对正在传递的数据进行json转换,但由于对象的StartDate和EndDate属性是DateTime对象,它似乎是json转换不喜欢它。
我已将模型更改为传递日期字符串,现在它正在按预期工作。
里克