我遇到了ASP.NET WebApi的问题,我不知道自己做错了什么。
只要客户端发出内容类型为XML的请求,就会出现问题。它完全适用于JSON。
(XmlSerializer和DataContractSerializer都会出现此问题)
我在干净的WebApi项目中重现了这个问题。这是测试控制器:
public class ValuesController : ApiController
{
private readonly Repository _repository = new Repository();
// GET /api/values
public IQueryable<Model> Get()
{
return _repository.Items;
}
// GET /api/values/5
public Model Get(int id)
{
return _repository.Items.FirstOrDefault(m => m.Id == id);
}
// POST /api/values
public HttpResponseMessage Post(Model model)
{
return new HttpResponseMessage<Model>(model, HttpStatusCode.OK);
}
}
public class Repository
{
public Repository()
{
_models = new List<Model>();
_models.Add(new Model { Id = 1, Name = "A", Values = new[]{"Foo", "Bar"} });
}
private readonly List<Model> _models;
public IQueryable<Model> Items
{
get { return _models.AsQueryable(); }
}
}
public class Model
{
public int Id { get; set; }
public string Name { get; set; }
public string[] Values { get; set; }
}
如您所见,Post方法只返回接收数据的回显。数据取自Get(int)方法的输出。
获取输出:
<?xml version="1.0" encoding="utf-8"?>
<ArrayOfModel xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Model>
<Id>1</Id>
<Name>A</Name>
<Values>
<string>Foo</string>
<string>Bar</string>
</Values>
</Model>
</ArrayOfModel>
发布请求:
POST http://localhost:50798/api/values HTTP/1.1
User-Agent: Fiddler
Host: localhost:50798
Accept: application/xml
Content-Type: application/xml
Content-Length: 110
<Model>
<Id>1</Id>
<Name>A</Name>
<Values>
<string>Foo</string>
<string>Bar</string>
</Values>
</Model>
发布回复正文:
<?xml version="1.0" encoding="utf-8"?>
<Model xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Id>1</Id>
<Name>A</Name>
<Values/>
</Model>
如前所述,JSON内容的一切正常。
答案 0 :(得分:0)
您可能遇到空值问题,请尝试更改
[serialize(IsNullable=true)]
public class Model