简体   繁体   中英

Calling a Rest WCF Service via HttpClient

I'm trying to call a WCF Rest service via Xamarin using HttpClient. I've tried numerous ways but I need to pass a custom type ideally.

We are getting Http Error 400 - Bad Request.

I've created a basic test to mimic what Xamarin does, and still get the same error. Here is the code:

WCF Service Interface/Method:

[OperationContract]
[WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "GetBookedContacts")]
    List<Contact> GetBookedContacts(ContactParameter contactParameter);

Testing Function:

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);


    }

We are converting the custom type using the Newtonsoft.Json library.

If i create another function on the same web service, with just a string parameter, it works fine.

It must be a type issue, but i have the types marked as follows in the web service:

[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'
    }
}

the problem is your date time format. you should set date time format. something like this:

   JsonSerializerSettings microsoftDateFormatSettings = new JsonSerializerSettings
   {
      DateFormatHandling = DateFormatHandling.MicrosoftDateFormat
  };

here you can read more.

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