Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WebAPI to Return XML

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.

like image 878
Matt Avatar asked Jul 26 '12 03:07

Matt


People also ask

Can Web API return XML?

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.

How do I return XML and JSON from Web API in .NET core?

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 { ... }

How do I return data from Web API?

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.


1 Answers

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.

like image 84
Arkadas Kilic Avatar answered Sep 20 '22 23:09

Arkadas Kilic