2011-03-08 67 views
0

我有一個簡單的restful wcf服務,我創建的只是爲了好玩。我試圖調用post方法,但我很失望。這裏是總結;wcf restful服務方法調用http錯誤的錯誤

這是我的服務合同界面;

namespace WcfServiceWithNortwind.Smooth { 

    [ ServiceContract] 
    public interface INorthwindService { 

     [ WebGet (UriTemplate = "/")] 
     [ OperationContract ] 
     List <Category2 > GetCategories(); 

     [ WebGet (UriTemplate = "categories/{id}")] 
     [ OperationContract ] 
     Category2 GetCategory(string id); 

     [ WebInvoke (UriTemplate = "categories/{id}" , Method = "DELETE")] 
     [ OperationContract ] 
     void DeleteCategory(string id); 

     [ WebInvoke (UriTemplate = "categories" , Method = "POST")] 
     void AddCategory(Category2 category); 

    } 
} 

這是我的服務的數據成員是Category2類;

namespace WcfServiceWithNortwind.Smooth { 

    [ DataContract] 
    public class Category2 { 

     [ DataMember ] 
     public int CategoryID { get; set ; } 

     [ DataMember ] 
     public string CategoryName { get; set ; } 

     [ DataMember ] 
     public string Description { get; set ; } 

    } 
} 

這是我試圖調用post方法的代碼;

System.Xml. XmlDocument doc = new System.Xml. XmlDocument(); 
    doc.Load(context.Server.MapPath("~/@xml/category.xml")); 

    string strHostAddress = "http://localhost:54860/Smooth/Nortwind.svc/categories" ; 

    string xmldata = doc.OuterXml; 
    string _data = String .Format("{0}{1}", "category=" , xmldata); 

    WebRequest _WebRequest = WebRequest .Create(strHostAddress); 
    _WebRequest.Method = "POST" ; 

    byte [] byteArray = Encoding .UTF8.GetBytes(_data); 
    _WebRequest.ContentType = "application/x-www-form-urlencoded" ; 
    _WebRequest.ContentLength = byteArray.Length; 

    Stream dataStream = _WebRequest.GetRequestStream(); 
    dataStream.Write(byteArray, 0, byteArray.Length); 
    dataStream.Close(); 

    var _response = _WebRequest.GetResponse(); 

這是我用來發送的xml文件,它是category.xml;

<? xml version =" 1.0 "?> 
<Category2> 
    <CategoryID /> 
    <CategoryName> Tugberk's Category </CategoryName> 
    <Description> .net, wcf, wpf, mvc, silverlight </Description> 
</Category2> 
當我運行的代碼

,我只要我嘗試_WebRequest.GetResponse()調用收到下面的錯誤;

傳入消息有一個 意外的消息格式'原始'。 操作的預期消息格式爲'Xml'; 'Json的'。這可以是 ,因爲未在綁定上配置WebContentTypeMapper的 。 有關更多詳細信息,請參閱 WebContentTypeMapper文檔。

我也試着用它的請求生成器函數發佈它與提琴手,我也有同樣的錯誤。

那麼我在這裏失蹤的傢伙?

回答

3

請確保您有頭的Content-Type:application/xml進行在您的要求,要麼設置的命名空間,你的XML負載從DataContract刪除的命名空間。像[DataContract(Namespace =「」)]

+0

我認爲問題也與名稱空間有關。我沒有時間去嘗試,但我會在今天。謝謝 ! – tugberk 2011-03-17 11:25:22

+0

我們可以看到解決方案到底有什麼成效嗎? – franklins 2012-09-24 12:16:43

1

變更請求的內容類型text/xml; charset=utf-8

+0

我用* application/xml來做到這一點; charset = utf-8 *,正如你用* text/xml; charset = utf-8 *表示的那樣。現在我得到這個例外;檢查類型爲WcfServiceWithNortwind.Smooth.Category2的對象的開始元素時出錯。根級別的數據無效。第1行,位置1. – tugberk 2011-03-09 07:22:44