Click here to Skip to main content
14,921,143 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I am using below code in web api .net core to get the request body content and it is working fine for JSON input ie., Content type - "application/json"

[HttpPost]
public void Post([FromBody] dynamic messages)
{}

But when I pass xml in request body ie., Content Type - "application/xml", exception was thrown 'Invalid Operation'. Is there any way we can get the request body content dynamically for XML input?

What I have tried:

Referred the below link
tps://www.hanselman.com/blog/TinyHappyFeatures2ASPNETWebAPIInVisualStudio2012.aspx


Quote:

Scott,

Do you know of anyway that a dynamic parameter will work for a request that contains XML?

For example:

POST http://localhost:52753/api/Test HTTP/1.1
User-Agent: Fiddler
Host: localhost:52753
Accept: application/xml
Content-Type: application/xml; charset=utf-8

<root>
<message>Hello


and have this bind into:

public dynamic Post([FromBody]dynamic xml)
{
return xml;
}

--------------------
Andy Cohen

Thursday, January 10, 2013 6:11:52 PM UTC

Andy - No, but this isn't a WebAPI issue. I don't think there are any XML parsers on .NET that use Dynamic. If there were, you could write a model binder quickly.
Posted
Updated 25-Jun-18 10:00am
v3
Comments
David_Wimbley 25-Jun-18 23:33pm
   
You labeled .net core so I'm not sure if this is same fix, but this worked in web api for me in .net 4.6

GlobalConfiguration.Configuration.Formatters.XmlFormatter.UseXmlSerializer = true;


You put that into your Global.asx within the Application_Start() method. Again, not sure if it is applicable in .net core as Im not as familiar with that but this is what i had to do to get xml to work.

Also to note, when doing this, I didn't need to use dynamic i just used the class name in the Controller action method signature. Ex: public IHttActionResult MyMethod([FromBody] MyxmlClass value)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900