How can I POST (as XML) an object to my ApiController using RestSharp?

心不动则不痛 提交于 2019-12-01 09:08:13

The issue above is because WebAPI is using the DataContractSerializer (as opposed to the XmlSerializer which is what you're after). To switch this around modify Global.asax as follows.

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

However, I suggest you use the RESTSharp formatters for WebAPI (instead of using the .Net formatters). This is particularly useful if you're DTO's have circular references (the .net fx serializers don't handle this too gracefully).

In Global.asax, modify the formatters by putting in

GlobalConfiguration.Configuration.Formatters.XmlFormatter = //RestSharp XML serializer here

A quick overview of serialization in WebAPI is here and worth a browse

I've had some issues with the AddBody calls not properly serializing JSON values, so there might be some similarity to your problem. Instead of AddBody, you could try:

request.AddParameter("text/xml", xmlAsString, ParameterType.RequestBody);

If that works, you could look to see about changing the second parameter to be the xml object and see if the serializer does what you want.

The other option could be the XmlMediaTypeFormatter.ReadFromStreamAsync isn't properly picking up a proper serializer; you could try overriding that function.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!