2013-01-07 25 views
2

OK隨身攜帶,所以我有一個MediaTypeFormatter:的ASP.NET Web API PUT操作參數不通過

public class iOSDeviceXmlFormatter : BufferedMediaTypeFormatter 
{ 
    public iOSDeviceXmlFormatter() { 
     SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/xml")); 
     SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/xml")); 
    } 
    public override bool CanReadType(Type type) { 
     if (type == typeof(iOSDevice)) { 
      return true; 
     } 
     return false; 
    } 

    public override object ReadFromStream(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger) { 
     iOSDevice device = null; 
     using (XmlReader reader = XmlReader.Create(readStream)) { 
      if (reader.ReadToFollowing("iOSDevice")) { 
       if (!reader.IsEmptyElement) { 
        device = new iOSDevice(); 
        ... do processing here ... 
       } 
      } 
     } 
     readStream.Close(); 
     return device; 
    } 

我有這樣的行動來處理PUT:

public void Put(string id, iOSDevice model) 
    { 
    } 

我已經試過這是好:

public void Put(string id, [FromBody]iOSDevice model) 
    { 
    } 

我已經試過這樣:

public void Put(string id, [FromBody]string value) 
    { 
    } 

沒有這些工作時,我這樣做:

string data = "<iOSDevice>xml_goes_here</iOSDevice>"; 
WebClient client = new WebClient(); 
client.UploadString(url, "PUT", data); 

行動拒絕觸發我iOSDeviceXmlFormatter,它甚至不會讀它作爲[FromBody]字符串。你如何得到這個東西來映射?

感謝,

佳佳

回答

2

您是如何註冊您的格式?您需要在第一個位置註冊此格式化程序,以便它優先於WebAPI的默認格式化程序。該代碼是這樣的:

config.Formatters.Insert(0, new iOSDeviceXmlFormatter()); 

這應該確保與內容類型的應用程序/ xml或text/xml的類型iOSDevice進來的任何請求使用格式化的反序列化。

+0

是的,這就是它!謝謝! –

2

您已經指定了您的格式將被觸發以下要求Content-Type頭:

SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/xml")); 
SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/xml")); 

可是你有沒有設置它們的請求。這就是爲什麼你的自定義格式化程序從不被激怒。所以,一旦你在全局配置進行註冊:

config.Formatters.Insert(0, new iOSDeviceXmlFormatter()); 

你應該確保您設置適當的請求Content-Type頭:

string data = "<iOSDevice>xml_goes_here</iOSDevice>"; 
using (WebClient client = new WebClient()) 
{ 
    // That's the important part that you are missing in your request 
    client.Headers[HttpRequestHeader.ContentType] = "text/xml"; 
    var result = client.UploadString(url, "PUT", data); 
} 

現在下面的動作將被trigerred:

public void Put(string id, iOSDevice model) 
{ 
} 

當然,您的自定義格式化程序將在之前被調用,以便從請求中實例化您的iOSDevice