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

后端 未结 2 1314
感动是毒
感动是毒 2021-01-14 12:43

I have an ASP.NET MVC4 website implementing a REST API, which I\'m consuming from a client application. My ApiController methods take and return complex objects, as XML.

相关标签:
2条回答
  • 2021-01-14 13:03

    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

    0 讨论(0)
  • 2021-01-14 13:10

    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.

    0 讨论(0)
提交回复
热议问题