我试图通过Xamarin使用HttpClient调用WCF Rest服务。我尝试了很多方法,但我需要理想地传递自定义类型。
我们收到Http Error 400 - Bad Request。
我已经创建了一个基本测试来模仿Xamarin的功能,但仍然会遇到同样的错误。这是代码:
WCF服务接口/方法:
[OperationContract]
[WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "GetBookedContacts")]
List<Contact> GetBookedContacts(ContactParameter contactParameter);
测试功能:
public async Task TestWebServiceCallAsync()
{
HttpClient client;
client = new HttpClient();
client.MaxResponseContentBufferSize = 256000;
ContactParameter cp = new ContactParameter();
cp.ApptDateFrom = DateTime.Now;
cp.ApptDateTo = DateTime.Now.AddDays(1);
cp.Code = "0001";
cp.Type = Enums.ContactType.Person;
string RestUrl = "http://testws/Rest/data.svc/GetBookedContacts";
var uri = new Uri(string.Format(RestUrl, string.Empty));
var json = JsonConvert.SerializeObject(cp);
var content = new StringContent(json, Encoding.UTF8, "application/json");
var response = await client.PostAsync(uri, content);
}
我们正在使用Newtonsoft.Json库转换自定义类型。
如果我在同一个Web服务上创建另一个函数,只有一个字符串参数,它可以正常工作。
它必须是类型问题,但我在Web服务中标记如下类型:
[DataContract]
public class ContactParameter
{
[DataMember]
public string Code { get; set; }
[DataMember]
public DateTime ApptDateTo { get; set; }
[DataMember]
public DateTime ApptDateFrom { get; set; }
[DataMember]
public Enums.Enums.ContactType Type { get; set; }
[DataMember]
public string Status { get; set; }
}
public class Enums
{
[DataContract]
public enum ContactType
{
[DataMember]
[EnumMember]
Person= 'P',
[DataMember]
[EnumMember]
Other= 'T'
}
}
答案 0 :(得分:1)
问题是您的日期时间格式。你应该设置日期时间格式。像这样的东西:
JsonSerializerSettings microsoftDateFormatSettings = new JsonSerializerSettings
{
DateFormatHandling = DateFormatHandling.MicrosoftDateFormat
};
here你可以阅读更多内容。