C# REST API: xml as post data

12,772

StartdDate.toString("s") did the trick.

Share:
12,772
Reinard
Author by

Reinard

BY DAY: I'm an dynamics Ax developer BY NIGHT: I'm a web developer (ASP.NET MVC) and Java application developer. With a keen interest in sending data over the web.

Updated on June 04, 2022

Comments

  • Reinard
    Reinard almost 2 years

    I'm working on a project which requires me to work with an REST API. The API expects a DTO as input parameter.

     [OperationContract]
            [WebInvoke(Method = "POST", UriTemplate = "campaign/create?session={sessionkey}", ResponseFormat = WebMessageFormat.Xml, BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Xml)]
            [XmlSerializerFormat(Style = OperationFormatStyle.Document, Use = OperationFormatUse.Literal)]
            FeedbackDTO PersistCampaign(string sessionkey, CampaignDTO PaycentoCampaign);
    

    I'm trying to send the data to this method with the following method:

    public static HttpWebResponse DoHttpWebRequest(String url, String method, string data)
    {
        HttpWebRequest req = WebRequest.Create(url) as HttpWebRequest;
        req.KeepAlive = false;
        req.ContentType = "application/xml";
        req.Method = method;
        if ((method.Equals("POST") || method.Equals("PUT")) && data != null)
        {
            byte[] buffer = Encoding.UTF8.GetBytes(data);
            Stream PostData = req.GetRequestStream();
            PostData.Write(buffer, 0, buffer.Length);
            PostData.Close();
        }
        return req.GetResponse() as HttpWebResponse;
    }
    

    After hours of debugging I found that the problem is caused by the DateTime proprties. I started to 'manually' create the XML and do property per property.

     sb.Append("<Startdate>").Append(HttpUtility.HtmlEncode(Startdate.ToString(Helper.DATE_FORMAT_STRING))).Append("</Startdate>");
    

    I tried adding a format (ddMMyyyy) in the toString but it's still causing a bad request. How should I add a DateTime property to the XML so ASP.NET is able to parse it into the DTO?

    Stuff I tried:

    • StartDate.ToLongDateString()
    • StartDate.ToString()
    • StartDate.toString("ddhhyyyy")
    • StartDate.Ticks