I try to get the output XML or JSON data based on my input. I used the below WEB API code but not able to exact output.
public string Get(int id) { if (GlobalConfiguration.Configuration.Formatters.XmlFormatter == null) { GlobalConfiguration.Configuration.Formatters.Add(GlobalConfiguration.Configuration.Formatters.XmlFormatter); } if (GlobalConfiguration.Configuration.Formatters.JsonFormatter == null) { GlobalConfiguration.Configuration.Formatters.Add(GlobalConfiguration.Configuration.Formatters.JsonFormatter); } if (id == 1) { GlobalConfiguration.Configuration.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.JsonFormatter); GlobalConfiguration.Configuration.Formatters.XmlFormatter.UseXmlSerializer = true; } else { GlobalConfiguration.Configuration.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter); GlobalConfiguration.Configuration.Formatters.JsonFormatter.UseDataContractJsonSerializer = true; } return "value"; }
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 { ... }
Web API provides media-type formatters for both JSON and XML. The framework inserts these formatters into the pipeline by default. Clients can request either JSON or XML in the Accept header of the HTTP request.
Add the below code app_start
event in global.asax
file. In API Url add the query string:
GlobalConfiguration.Configuration.Formatters.JsonFormatter.MediaTypeMappings.Add( new QueryStringMapping("type", "json", new MediaTypeHeaderValue("application/json"))); GlobalConfiguration.Configuration.Formatters.XmlFormatter.MediaTypeMappings.Add( new QueryStringMapping("type", "xml", new MediaTypeHeaderValue("application/xml")));
e.g.:
for xml : http://localhost:49533/api/?type=xml for json: http://localhost:49533/api/?type=json
What you are trying to do will not work in a multi-threaded environment. You cannot add to and remove from the formatters collection on a per-request basis. Here is a better way of accomplishing what you want.
public HttpResponseMessage Get(int id) { Foo foo = new Foo(); var content = new ObjectContent<Foo>(foo, ((id == 1) ? Configuration.Formatters.XmlFormatter : Configuration.Formatters.JsonFormatter)); return new HttpResponseMessage() { Content = content }; }
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