I'm wanting my WEB API method to return an XML object back to the calling application. Currently it's just returning the XML as a string object. Is this a no no? If so how do you tell the webapi get method that it's returning an object of type XML?
Thanks
Edit: An example of the Get method:
[AcceptVerbs("GET")] public HttpResponseMessage Get(int tenantID, string dataType, string ActionName) { List<string> SQLResult = MyWebSite_DataProvidor.DB.spReturnXMLData ("SELECT * FROM vwContactListing FOR XML AUTO, ELEMENTS").ToList(); string AllResults = ""; for (int i = 0; i < SQLResult.Count - 1; i++) { AllResults += SQLResult[i]; } string sSyncData = "<?xml version=\"1.0\"?> " + AllResults; HttpResponseMessage response = new HttpResponseMessage(); response.Content = new StringContent(sSyncData); return response; }
Its a bit hacky because im still at the prototyping stage. Will refactor when i can prove its doable.
the Web API 2 framework defaults to XML but uses the client's accept header to determine the return type format. If XML is required for every response then configure Web API to always return XML.
In order to return XML using an IActionResult method, you should also use the [Produces] attribute, which can be set to “application/xml” at the API Controller level. [Produces("application/xml")] [Route("api/[controller]")] [ApiController] public class LearningResourcesController : ControllerBase { ... }
Learn the three ways you can return data from your ASP.NET Core Web API action methods. We have three ways to return data and HTTP status codes from an action method in ASP.NET Core. You can return a specific type, return an instance of type IActionResult, or return an instance of type ActionResult.
If you don't want the controller to decide the return object type, you should set your method return type as System.Net.Http.HttpResponseMessage
and use the below code to return the XML.
public HttpResponseMessage Authenticate() { //process the request ......... string XML="<note><body>Message content</body></note>"; return new HttpResponseMessage() { Content = new StringContent(XML, Encoding.UTF8, "application/xml") }; }
This is the quickest way to always return XML from Web API.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With