2013-10-06 34 views
2

我在此處使用示例http://www.asp.net/web-api/overview/creating-web-apis/creating-a-web-api-that-supports-crud-operations,但我無法使其從Chrome郵遞員插件接收郵寄請求。當使用Chrome郵遞員插件時,Web Api Post值始終爲空

這裏是我發佈的XML的一個例子。我已經將Postman中的Content-Type標頭設置爲application/xml。

<?xml version="1.0" encoding="ISO-8859-1"?> 
<Product> 
    <Category>Groceries</Category> 
    <Name>New From Post</Name> 
    <Price>1.39</Price> 
</Product> 

我也曾嘗試以下解決方案Model always null on XML POST但它似乎並沒有任何區別。這是我的WebApiConfig文件。

public static void Register(HttpConfiguration config) 
     { 

      config.Formatters.Add(new XmlMediaTypeFormatter()); 
      config.Formatters.XmlFormatter.UseXmlSerializer = true; 

      config.Routes.MapHttpRoute(
       name: "DefaultApi", 
       routeTemplate: "api/{controller}/{id}", 
       defaults: new { id = RouteParameter.Optional } 
      ); 
     } 

我絕對打到了正確的終點,我可以看到當我調試它的項目爲null。

public HttpResponseMessage PostProduct(Product item) 
     { 
      item = repository.Add(item); 
      var response = Request.CreateResponse(HttpStatusCode.Created, item); 

      string uri = Url.Link("DefaultApi", new { id = item.Id }); 
      response.Headers.Location = new Uri(uri); 
      return response; 
     } 

任何想法?

編輯:此外,這似乎工作正常,當我張貼與json相同的值。我真的需要能夠用xml來測試這個。

回答

1

DataContract這樣應用到你的DTO類。

[DataContract(Namespace="")] 
public class Product 
{ 
    public int Id { get; set; } 
    public string Name { get; set; } 
    public string Category { get; set; } 
    public decimal Price { get; set; } 
} 

或者,發送正確的命名空間信息。

+0

不要忘記將[DataMember]屬性添加到屬性,否則它們也不會被反序列化。 –