當我針對創建的RESTful Web服務運行客戶端時,我得到一個{"The remote server returned an error: (415) Unsupported Media Type."}
。內容類型在客戶端中是正確的。該服務在vs 2010中的WCF測試客戶端下正確運行。我認爲我的問題出現在我的客戶端代碼中,或者我發送/格式化XML的方式。任何意見是極大的讚賞。RESTful WCF返回錯誤代碼415?
使用VS2010,.NET4
Web服務代碼:
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>