Setting a specific Brotli compression level when using response compression in ASP.NET Core

Brotli can compress HTML, CSS and JS files more than Gzip. If you can’t enable Brotli compression on the server level but want to use it in your ASP.NET Core app you can use the response compression middleware to enable it from your Startup.cs file. Setup is easy and looks like below..

Setting up MVC response compression

Note the app.UseResponseCompression() in the Configure method needs to be before app.UseStaticFiles() as otherwise headers have already been sent. The default setup above will use Brotli if the client supports it else it will use Gzip if it’s supported. By default the Brotli compression provider will be set to a compression level of 1 (fastest).

The compression level corresponds to how aggressive an algorithm will compress a document. Brotli has 11 levels, 1 being the fastest but least compressed and 11 being the most compressed but also the slowest. Brotli at its highest level (11) is extremely slow compared to Gzip at its highest level (9). Slow compression is fine for static CSS/JS files which we can compress ahead of time. For on the fly compression (eg. dynamic web pages) slow speeds can negatively impact web app performance..

SO

.. for Brotli compression to be advantageous over Gzip we need to find the compression level which gives us the best balance between compression amount and speed..

BUT

the problem with the Brotli compression provider in ASP.NET Core is that it only has three options in its enum for setting the level…

ResponseCompression Options

There is no enum option for the best balance between compression and speed. In this case we can just set the level with a number directly…

Setting Brotli Level

You need to experiment with different levels but a number of resources seem to be agreeing on level 4 or 5 as being the sweet spot…

https://blogs.akamai.com/2016/02/understanding-brotlis-potential.html

https://paulcalvano.com/2018-07-25-brotli-compression-how-much-will-it-reduce-your-content

https://quixdb.github.io/squash-benchmark/#results-table

Of course for your static content such as CS, JS, Fonts etc. compress to the max with 11. This will give you significant byte savings over Gzip.

 

Creating a DTO class from a JSON string in Visual Studio

If you’ve got back some JSON from a REST API you’ll likely be wanting to use Newtonsoft or System.Text.Json (.NET Core 3.0) to deserialize that JSON into a .NET DTO class to make working with it easier.

To create the DTO you can

1 – Manually examine the JSON and manually create the C# class or
2 – Use an online JSON to C# convertor such as jsonformatter.org or
3 – Use Visual Studios Paste Special -> Paste JSON as Classes option.

Paste JSON as Classes in Visual Studio

This is a little known feature of Visual Studio and is simple to use. For example if I copied the following JSON (taken from json.org/example.html) into my clipboard ..

JSON example

and selected Paste Special -> Paste JSON As Classes from the Edit menu ..

Paste JSON As Classes

Visual Studio would create the following classes ..

Visual Studio generated classes

which you can easily create an instance of by deserializing the same JSON string.

Convert JSON to object

This is a lot easier than manually creating the DTO and while many of the convertors online are great having something like this built in is better. And as you may have noticed above there’s also a Paste XML As Classes option too if you need it.

Extracting Google PageSpeed performance score in .NET

Most webmasters are aware that Google uses performance as a ranking signal for both desktop and mobile searches so its important your site is as fast as it can be. You can check your performance score according to Google in Chrome developer tools or online but since they provide a HTTP API you can get also get performance scores programmatically.

Calling the PageSpeed HTTP API and Serializing the JSON response into a DTO

Calling the API is easy as its a simple GET request as can be seen below…

How to call the PageSpeed API

You just need to make sure you set your key (you can get one from here but a key is not needed if your just testing) and the URL which you want to run the performance check for as query params. You can see above I’ve also set strategy which will default to ‘DESKTOP’ if not set.

After the response comes back (not very fast as the performance check takes a few seconds) I use the new System.Text.Json serializer released in .NET Core 3.0 to convert it into a simple DTO which matches the structure of the JSON. The performance score itself is located in lighthouseResult -> categories -> performance -> score.

As you can see to adhere with VS naming conventions I’ve made the properties start with uppercase and therefore needed to set the PropertyNameCasesInsentive flag above as otherwise the DTO would be empty after serialization.

Simple DTO for storing PageSpeed results

Calling the PageSpeed HTTP API and querying the JSON directly using JsonDocument

The above is nice and neat as we now have a strongly typed object which we could pass to our views etc. In this case however we only care about one property, the performance score itself so having to create a nested class or DTO just for this seems like a lot of effort.

Rather than serializing we can alternatively use JsonDocument and query the JSON string directly by chaining a couple of GetProperty calls together.

Use GetProperty to read JSON properties

Of course to use GetProperty you need to be sure the property will always exist in your JSON as otherwise an exception will be thrown. If your not sure about this use TryGetProperty instead and check if you’ve successfully got an element before moving on…

Use TryGetProperty to read JSON properties

Google PageSpeed Insights API Client Library for .NET

Google also has a PageSpeed API Client Library for .NET however I’ve not really looked into it much yet. Using this library over simple HTTP requests should allow you to have a more strongly typed approach where you don’t have to worry about matching JSON property names etc.

Parsing a nested value from a JSON string in .NET Core 3 without needing a DTO

.NET doesn’t use Newtonsoft by default anymore (since .NET Core 3.0). A lot of the examples online show how to use the new System.Text.Json namespace to extract values from JSON strings by deserializing the strings into full POCO classes (DTOs/ViewModels).

If you only want to extract the value of a particular property and don’t want the overhead of having to create a lot of nested classes, its very simple to extract values directly using the JsonDocument class.

For example if I have the following nested JSON structure (taken from Google PageSpeed API in case your curious) ..

PageSpeed nested JSON Structure

and

I want to extract the 0.82 score value I can just create a new instance of a JsonDocument and then chain a couple of GetProperty calls together.

How to read nested values in System.Text.Json

Of course to use GetProperty you need to be sure the property will always exist in your JSON as otherwise an exception will be thrown. If your not sure about this use TryGetProperty instead and check if you’ve successfully got an element before moving on…

TryGetProperty method