Gert Kommer
Gert Kommer

Reputation: 1243

Send Xml data to webapi apicontroller parameter value null

I want to send xmldata via fiddler to my wepabi, but my webapi doesn't get the data for some reason. I want to know the reason;)

What I have:

[RoutePrefix("Document")]
public class DocumentController : ApiController
{
    [HttpPost]
    [Route("AddDocument")]
    public IHttpActionResult AddDocument([FromBody] XmlDocument doc)
    {
        //  Do Stuff
        return Ok();
    }
}

What my fiddler looks like FiddlerRequest

When I do this request doc is always null. What am I doing wrong?

Upvotes: 0

Views: 1115

Answers (1)

peco
peco

Reputation: 4000

In order to use content negotiation you need to accept a class which the model binder can bind to in your controller. Like this:

public class Document
{
    public int Id { get; set; }
    public string BaseUrl { get; set; }
    public string Name { get; set; }
    public int Active { get; set; }
    public Page[] Pages { get; set; }
}

public class Page
{
    public int Id { get; set; }
    public string Url { get; set; }
    public string InternalId { get; set; }
    public string Name { get; set; }
    public bool Active { get; set; }
}

Then you accept this as your argument instead of a XmlDocument:

[RoutePrefix("Document")]
public class DocumentController : ApiController
{
    [HttpPost]
    [Route("AddDocument")]
    public IHttpActionResult AddDocument([FromBody] Document doc)
    {
        //  Do Stuff
        return Ok();
    }
}

And now you can change the Content-Type header in your request to be either application/xml, text/xml or application/json depending on the format being posted.

Upvotes: 1

Related Questions