1

I'm stuck with a problem with ASP.NET WebApi and I don't know if I'm doing something wrong.

The problem happens whenever the client makes a request whose content type is XML. It perfectly works with JSON.

(this problem happens both with XmlSerializer and DataContractSerializer)

I reproduced the problem on a clean WebApi project. Here is the test controller:

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; }
}

As you can see, the Post method is just returning an echo of the received data. The data is taken from the output of the Get(int) method.

Get output:

<?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 request:

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>

Post response body:

<?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>

As already said, everything works just fine with JSON content.

Peter O.
  • 32,158
  • 14
  • 82
  • 96
Kralizek
  • 1,999
  • 1
  • 28
  • 47
  • possible duplicate of [Deserialization / model binding in MVC4 webapi does not work with arrays](http://stackoverflow.com/questions/9592838/deserialization-model-binding-in-mvc4-webapi-does-not-work-with-arrays) – carlosfigueira May 18 '12 at 07:41
  • @carlosfigueira definitely a duplicate. I couldn't find that question myself. – Kralizek May 18 '12 at 08:09

1 Answers1

0

you might have problem with null values so please try to change

[serialize(IsNullable=true)]
public class Model