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

后端 未结 2 1348
感动是毒
感动是毒 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

提交回复
热议问题