This section will describe how to use Liquid XML Objects within ASP.Net MVC web applications.
The rest of the section assumes you have generated a set of Liquid XML Objects from an XSD schema. It is assumed that the schema contains a root xs:element called 'MyRoot', and a corresponding C# class called 'MyRootElm' has been generated to represent this XML element.
The following shows how to accept and return a Liquid XML generated object from an MVC controller class.
The first step is to use the generated class within your controller.
MVC Controller Code |
Copy Code
|
---|---|
public class MyController : Controller { [HttpGet] public MyRootElm TestReturn() { MyRootElm elm = new MyRootElm(); // ... return elm; } [HttpPost] public void TestArgument([FromBody] MyRootElm elm) { // ... } } |
If you use the code as it is, it will work, but the formatter used to serialize the data will the XmlMediaTypeFormatter, which will not correctly format/interpret the XML data.
In order to use the Liquid XML Objects formatter, we need to register it with the MVC framework.
The MVC specific code is in a separate Nuget called LiquidTechnologies.XmlObjects.Runtime.Web, so ensure this is present in your MVC project.
The Liquid XML Object Media formatters must be registered with the MVC framework.
The Liquid XML formatters can be registered using the extension method AddLxFormatters on the IServiceCollection collection.
Registering the Liquid XML Objects Formatters using MVC (.Net Core) |
Copy Code
|
---|---|
public class Startup { public void ConfigureServices(IServiceCollection services) { services.AddControllersWithViews(); services.AddMvc(); services.AddLxFormatters(); |
An instance of the LxMediaTypeFormatter class must be registered in the HttpConfiguration.Formatters collection, and it must appear before the default XmlMediaTypeFormatter (which should already have been registered by the .net framework), this can be achieved by inserting it at the front of the collection.
Registering the Liquid XML Objects Formatters using MVC (.Net Framework) |
Copy Code
|
---|---|
public static class WebApiConfig { public static void Register(HttpConfiguration config) { // Web API routes config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); config.Formatters.Insert(0, new LxMediaTypeFormatter()); } } |
The LxMediaTypeFormatter and the extension method AddLxFormatters, both take 3 options parameters that allow the control of the serialization to be controlled.
Values setup here will be applied to all serialization/deserialization performed when objects are passed in and out of controller web methods.