【发布时间】:2011-11-08 01:46:11
【问题描述】:
当我针对我创建的 RESTful Web 服务运行客户端时,我收到了 {"The remote server returned an error: (415) Unsupported Media Type."}。客户端中的内容类型正确。该服务在 vs 2010 中的 WCF 测试客户端下正常运行。我认为我的问题出在我的客户端代码或我发送/格式化 XML 的方式中。非常感谢任何建议。
使用VS2010,.net4
网络服务代码:
public Charge GetCharge(Charge aCharge)
{
return aCharge;
}
[ServiceContract(Namespace = "http://www.test.com/Charge")]
public interface IService1
{
[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "getcharge",
RequestFormat = WebMessageFormat.Xml,
ResponseFormat = WebMessageFormat.Xml,
BodyStyle = WebMessageBodyStyle.Bare)]
Charge GetCharge(Charge aCharge);
}
// Use a data contract as illustrated in the sample below to add composite types to service operations.
[DataContract(Namespace = "http://www.test.com/Charge")]
public class Charge
{
[DataMember]
public string ID
{
get;
set;
}
[DataMember]
public string Hours
{
get;
set;
}
[DataMember]
public string Comment
{
get;
set;
}
[DataMember]
public string DateT
{
get;
set;
}
}
客户端代码:
HttpWebRequest req = null;
HttpWebResponse res = null;
try
{
string url = "http://localhost:1657/Service1.svc/getcharge";
req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "POST";
req.ContentType = "application/xml";
req.Timeout = 30000;
req.Headers.Add("SOAPAction", url);
System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
xmlDoc.XmlResolver = null;
xmlDoc.Load(@"c:\file\benCharge.xml");
string sXML = xmlDoc.InnerXml;
req.ContentLength = sXML.Length;
System.IO.StreamWriter sw = new System.IO.StreamWriter(req.GetRequestStream());
sw.Write(sXML);
sw.Close();
res = (HttpWebResponse)req.GetResponse();
}
catch (Exception ex)
{
System.Console.WriteLine(ex.Message);
}
客户端 XML:
<Charge xmlns="http://www.test.com/Charge"><ID>1</ID><Hours>10</Hours><Comment>Mobile app development</Comment><DateT>01/01/2011</DateT></Charge>
【问题讨论】:
标签: .net wcf web-services rest httpresponse