我正在尝试将一些XML发布到Web服务,每次我都会收到400 Bad Request错误。
在MyService.cs中:
[ServiceContract(Namespace = "http://foo")]
public class MyService
{
[OperationContract, WebInvoke(UriTemplate = "/GetData/", RequestFormat = WebMessageFormat.Xml, ResponseFormat = WebMessageFormat.Xml, BodyStyle = WebMessageBodyStyle.Bare, Method = "POST")]
public string GetData(DataRequest req)
{
return "Success!";
}
}
[DataContract(Namespace = "http://foo")]
public class DataRequest
{
[DataMember]
public string ID { get; set; }
[DataMember]
public string Data { get; set; }
}
在单独的控制台应用程序Program.cs中:
Path p = "C:\\Users\\sflan\\Desktop\\test.xml";
string url = "http://foo/MyService.svc/GetData/";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "POST";
req.ContentType = "application/xml";
byte[] data = Encoding.UTF8.GetBytes(p.readFile());
req.ContentLength = data.Length;
using (Stream s = req.GetRequestStream())
{
s.Write(data, 0, data.Length);
s.Close();
}
try
{
WebResponse response = req.GetResponse();
using (StreamReader rdr = new StreamReader(response.GetResponseStream()))
{
Console.WriteLine(rdr.ReadToEnd());
rdr.Close();
}
}
catch (Exception ex) { Console.WriteLine(ex.Message); }
我试图在文件中发送的XML:
<root>
<Users ID="2" Data="This is some sample data." />
</root>
我搜索了几个小时寻找解决方案,但一直找不到。我的web.config允许最大缓冲区大小/ poolsize和我能找到的所有相关内容,但仍然没有运气。值得注意的是,如果我从GetData方法签名中删除“DataRequest req”,我会得到我的成功消息,但我需要能够使用XML数据。
谁能告诉我我做错了什么?
答案 0 :(得分:1)
XML的格式很差,我不会从以同一问题为中心的帖子中找到答案。
适当的XML如下:
<DataRequest xmlns="http://foo">
<Data>This is some sample data.</Data>
<ID>2</ID>
</DataRequest>