7 steps to increase your ASP.NET website performance

The performance of a website is one of the most important things that will improve your SEO ranking and the number of visitors.

There are many studies that show how improved website speed leads to more visitors and ultimately more money.

ASP.NET Core is a good choice to create a fast website, but there are some things that can take your website performance and optimization to the next level.

Upgrade all the libraries and the framework

Update your site every time to use the latest technologies, both for the backend and the client-side. Usually, a new library contains less redundant code and uses new features that are more powerful.

.NET Framework

For example, ASP.NET Core can handle 2300% more requests than the previous ASP.NET Framework 4.6. Also, the latest libraries include bug fixes and are more secure.

Javascript and CSS Libraries

If you are using Bootstrap, try upgrading to version 5. This version does not require JQuery.

If you still want to use features of JQuery, take a look at Zepto.js first. This library is largely JQuery compatible and built-in modules. You can use only the modules you need and reduce the size of the library.

Optimize images

Typically, images take up a lot of space and can cause major speed issues when you try to display them in your users’ browsers.

Use the new image formats

WebP format is better optimized than older formats such as PNG and JPEG. You can use image conversion tools to convert your images to this format or you can automate this step by using a Gulp plugin for WebP.

You can also use the AVIF format, which is even more compressed than WebP. Note, however, that AVIF is not yet supported by all browsers, so you will need to use a backup.

Specify the height and width attributes

Every time you use the HTML <img> attribute, specify the height and width value in the attributes. This way, the browser reserves that space until the image is rendered.

Use lazy load

Most browsers support the HTML loading attribute for images and iframes.

Using this attribute you can specify that your images should only not load until a user scrolls near them. So if the image tag doesn’t appear at the top, the image will not load. This feature increases the speed because the browsers only load what the user sees.

<img src="/images/movie.jpg" alt="Movie poster" width="185" height="277" loading="lazy"/>

Bundle and minify your files

The minification process removes all the whitespace and comments, shortened your name variables, and removes unnecessary code. This will reduce the size of your files.

CSS and Javascript files

The bundling process combines all script files into a single file. This is available also for CSS files.

I personally use Bundler & Minifier extension. This allows you to minify and bundle your files during the build step.

HTML files

The Bundler&Minifier extension will not minify your cshtml files, because it contains Razor syntax and server-side code that is executed at runtime.

One approach to this is to use the WebMarkupMin library. This library will minify your HTML at runtime, so it won’t deal with the razor syntax or asp tag helpers.

The WebMarkup library also minifies the javascript from your scripts tag and the CSS from the styles tag.

Remove unused CSS

If you use Bootstrap or any other stylesheet library, you will end up with a lot of rules that you load and do not use. So, you should remove the unused rules.

You can remove the unused rules using the Gulp plugin purgecss. With this plugin, you specify the stylesheet file and where you use it. The plugin removes the styles which are not used in the HTML pages.

gulp.task('purgecss', () => {
    return gulp.src(['./wwwroot/lib/bootstrap/dist/css/bootstrap.css'])
        .pipe(purgecss({
            content: ['./Views/**/*.cshtml', './Pages/**/*.cshtml', './Areas/Identity/**/*.cshtml', './Areas/Identity/Pages/Account/**/*.cshtml'],
            safelist: [/modal-.*/]
        }))
        .pipe(gulp.dest('./wwwroot/css'))
})

Content Delivery Network

A Content Delivery Network or CDN can serve your resource files to users from the nearest server.

A CDN is a network of distributed servers that can store and cache your Javascript, CSS, and other resources.

When a user requests a resource, the CDN delivers it from the closest server. This way, the resource is delivered faster and you save bandwidth.CDN Map

Personally, I prefer to useĀ Cloudflare CDN. It is free and also offers HTTP/2 and HTTP/3 support, firewalls, compression, and DDoS protection.

ASP.NET Caching

Response Caching Middleware

Based on the headers of the request and using attributes for controllers and actions, you can provide a cached version of a page. If you want to enable response caching, you need to call AddResponseCaching for your services and enableĀ response caching middleware.

If you don’t use a CDN like Cloudflare, you should at least enable caching for the static files. Modify the UseStaticFiles call with this one:

app.UseStaticFiles(new StaticFileOptions
{
    OnPrepareResponse = ctx =>
    {
        const int durationInSeconds = 60 * 60 * 24 * 7; // 60 seconds (1 minute) * 60 minutes (1 hour) * 24 hours * 7 days
        ctx.Context.Response.Headers[HeaderNames.CacheControl] =
            "public,max-age=" + durationInSeconds;
    }
});

In-memory Cache

Using IMemoryCache you can store in-memory objects or values that are expensive to get.

For example, you call a service to see if a slot is available. When the slot is taken, a new slot is available after two hours, but the user retries to see if it’s available. You can cache the result and return the result to users without calling again the service.

A great way to reduce the requests is to cache your Entity Framework and database queries. You will save your users a lot of time when they need common data. You can use libraries like Entity Framework Plus or EFCoreSecondLevelCacheInterceptor. With one of these libraries you can easily cache and retrieve data:

_context.Foods.Cacheable(CacheExpirationMode.Absolute, TimeSpan.FromMinutes(240)).AsNoTracking()

Response Compression

The responses can be compressed to have a lower size, which can be transferred quickly over the network. To compress the responses you should add the following service services.AddResponseCompression(); and call on an instance of IApplicationBuilder the method app.UseResponseCompression();.

By default, the Brotli, and Gzip compression methods will be enabled. Only a couple of MIME Types will be compressed. Most of the file formats are already compressed, so a new compression will produce overhead. PNG files are a great example of a compressed format.

4 thoughts on “7 steps to increase your ASP.NET website performance”

Leave a Comment