I would like to create a web application that returns data in the form of XML or JSON, how do I go about doing this?
The model:
namespace ReturningJSONandXML.Models
{
public class SomeImportantInformation
{
public int ID { get; set; }
public string Information { get; set; }
}
}
The controller:
namespace ReturningJSONandXML.Controllers
{
public class GetInfoController : Controller
{
// GET: /<controller>/
public List<SomeImportantInformation> Get()
{
List<SomeImportantInformation> ImportantInfo = new List<SomeImportantInformation>();
ImportantInfo.Add(new SomeImportantInformation { ID = 0, Information = "Awesome info" });
ImportantInfo.Add(new SomeImportantInformation { ID = 1, Information = "Some other interesting info" });
return ImportantInfo;
}
}
}
I would like to return an XML and JSON file...
What are the best practice's I should be using here?
with core 2, you need to specifically add the options to the mvc serverice to enable xml input/output:
and then change the Accept header to:
application/xml or application/json
In ASP.Net Core 2.0 you can use eve shorter syntax.
In Startup class in ConfigureServices method, you should have:
And controller that accepts complex object looks like this:
This is an XML to send:
And the same as json:
And that’s it! Sending the same document either in XML or Json to api/documents/SendDocument endpoint just work. Only remember about correct Content-Type header in your request.
You can read the whole post at my blog: http://www.michalbialecki.com/2018/04/25/accept-xml-request-in-asp-net-mvc-controller/
The framework takes care automatically for you, so you don´t have to reinvent the wheel. The answer is quoted below. But to make it simpler: Unless you specify an Accept header, the API will serialize the response as JSON. If you specify for example 'application/xml' it will return XML. As MSDN Says:
https://docs.microsoft.com/en-us/aspnet/core/mvc/models/formatting