Model builders
We continue the previous example by adding more content, this time in the form of a model. The content is placed in a separate class TestPageModel, and it is built using a TestPageModelBuilder class.
Seperating out the content data into a "model" class is part of the MVC design pattern.
In the example model, we just add two numbers weight and height. We create it under "Models\Site" and add the TestPageModel.cs, inherit from PageModel to give common base class functionality.
public class TestPageModel : PageModel
{
public int Height { get; set; }
public decimal Weight { get; set; }
}
We use a model builder class to seperate out the the model building. We apply the service attribute to the class, so it can be injected to the TestPageController constructor.
using Litium.Runtime.DependencyInjection;
namespace Litium.AddOns.HeadlessApi.Models.Site.Builders
{
[Service(Lifetime = DependencyLifetime.Singleton, ServiceType = typeof(TestPageModelBuilder))]
public class TestPageModelBuilder
{
private const int initialHeight = 181;
private const decimal initialWeight = 50;
public TestPageModel Build()
{
return new TestPageModel()
{
Weight = initialWeight,
Height = initialHeight
};
}
}
}
We modify the TestPageController, with model builder injected into constructor. We use the ModelBuilder to build the test page model.
For the webapit swagger documentation, we apply the ResponseType Attribute, so the response type in generated documentation is correct.
using Litium.AddOns.HeadlessApi.Models.Site;
using Litium.AddOns.HeadlessApi.Models.Site.Builders;
using System.Web.Http;
using System.Web.Http.Description;
namespace Litium.AddOns.HeadlessApi.Controllers.Site
{
[RoutePrefix(Routes.RootUri + "/TestPage")]
public class TestPageController:HeadlessApiControllerBase
{
private readonly TestPageModelBuilder _testPageModelBuilder;
public TestPageController(TestPageModelBuilder testPageModelBuilder)
{
_testPageModelBuilder = testPageModelBuilder;
}
[HttpGet]
[Route("", Name = "TestPage")]
[ResponseType(typeof(TestPageModel))]
public IHttpActionResult Get()
{
var model = _testPageModelBuilder.Build();
if (model == null)
{
return NotFound();
}
return Ok(model);
}
}
}
This produces the following output in Postman

And the generated web-api documentation would look as follows.
