How to Return Json, XML and Other Response Types from a Dotvvm Application

Vincent Nwonah
DotVVM
Published in
2 min readAug 26, 2020
Dotvvm Logo

Sometimes, It becomes necessary that we create an endpoint in our web application that returns some JSON, XML or other response format that isn’t html. A good example of this scenario is for health checks, we want to create an endpoint that an orchestrator like Kubernetes, can call to find out the health of the system, this endpoint will be required to return JSON formatted response to the orchestrator or health checker.

Creating view models allows us return just html, however, Dotvvm has a nice feature called Presenters which we will be using to implement the desired feature.

Dotvvm Presenters

Dotvvm presenters are a lightweight alternative to middleware that let you intercept an incoming http request at a particular URL and return a response.

Code Example

We will be working with the starter Dotvvm CRUD project that lets us create, view, edit and delete students.

Add a folder called presenters to the root of your project and add the class below to the folder

We make this class a Presenter by inheriting from the IDotvvmPresenter Interface and implementing the ProcessRequest method. I am also injecting the StudentDbContext as I want to check that the database is reachable before returning a healthy report.

You can perform any other checks in the ProcessRequest method, and return a response based on the result of these checks.

For our example, I am returning JSON, but you could return XML or plaintext.

To use this class open Startup.cs and register it in ConfigureServices with the line

services.AddTransient<HealthCheckPresenter>();

We now need to configure the endpoint our Presenter responds to. To do this, open the DotvvmStartup.cs file and add the line

config.RouteTable.Add(“Health_Endpoint”, “health”, typeof(HealthCheckPresenter));

to the ConfigureRoutes method.

Run the application now and navigate to /health and you should see the JSON response. You can now configure other services to call that endpoint to get the health, or any information you want to expose of your web app.

Conclusion

In this post we see that returning other content types with Dotvvm is pretty straightforward, reach out to me if you have any challenges.

Thanks for reading.

--

--