我正在从事一个需要使用 REST API 的项目。 API 需要一个 DTO 作为输入参数。
[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);
我正在尝试使用以下方法将数据发送到此方法:
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;
}
经过几个小时的调试,我发现问题是由 DateTime 属性引起的。我开始“手动”创建 XML 并为每个属性创建属性。
sb.Append("<Startdate>").Append(HttpUtility.HtmlEncode(Startdate.ToString(Helper.DATE_FORMAT_STRING))).Append("</Startdate>");
我尝试在 toString 中添加格式 (ddMMyyyy),但它仍然导致错误请求。我应该如何将 DateTime 属性添加到 XML,以便 ASP.NET 能够将其解析为 DTO?
我尝试过的东西:
- StartDate.ToLongDateString()
- StartDate.ToString()
- StartDate.toString("ddhhyyyy")
- 开始日期.Ticks
最佳答案
StartdDate.toString("s") 成功了。
关于C# REST API : xml as post data,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10280326/