joydip_kanjilal
Contributor

How to use the Save-Data request header in ASP.Net Core

how-to
Mar 04, 20194 mins
C#Microsoft .NETSoftware Development

Take advantage of the data-saving mode in Chrome and Opera browsers to deliver lighter and faster ASP.Net Core applications

fast pace / business-technolgy-computing speed
Credit: Thinkstock

HTTP headers contain data stored as name/value pairs that are passed between the server and the client. These headers are passed along with the request or the response. The Save-Data header is a “client hint” request header that is available in Chrome and Opera web browsers.

The Save-Data request header enables you to build applications that are lighter and faster for users who turn on a data-saving mode in their web browsers. If the data-saving mode is enabled, the web browser sends a HTTP request header named Save-Data with the value “on.” You can enable this extension in Chrome to enable Google servers to compress pages before they are rendered. It should be noted that you can also enable the data-saving mode in Android from the settings menu.

Save-Data is a great performance optimization trick that you can take advantage of to deliver faster, lighter web applications—often by replacing high-resolution images with low-res versions or omitting non-essential images altogether. This article presents a discussion of how we can work with the Save-Data request header in ASP.Net Core applications.

Create an ASP.Net Core web application project

First off, let’s create an ASP.Net Core project. If Visual Studio 2017 is up and running in your system, follow the steps given below to create a new ASP.Net Core web application project in Visual Studio.

  1. Launch the Visual Studio 2017 IDE.
  2. Click on File > New > Project.
  3. Select “ASP.Net Core Web Application (.Net Core)” from the list of the templates displayed.
  4. Specify a name for the project.
  5. Click OK to save the project.
  6. A new window “New .Net Core Web Application…” is shown next.
  7. Select .Net Core as the runtime and ASP.Net Core 2.2 (or later) from the drop-down list at the top.
  8. Select API as the project template
  9. Ensure that the check boxes “Enable Docker Support” and “Configure for HTTPS” are unchecked as we won’t be using those features here.
  10. Ensure that “No Authentication” is selected as we won’t be using authentication either.
  11. Click OK.

Following these steps will create a new ASP.Net Core project in Visual Studio. In the next section we’ll examine how we can work with the Save-Data header in the ASP.Net project we just created.

Create the Save-Data header middleware in ASP.Net Core

We’ll now build a middleware that will check if the Save-Data header is enabled. If Save-Data is enabled, the middleware will send an optimized response. Right-click on the project you created earlier and select “Add -> Class…” to create a new C# code file. Name this file SaveDataMiddleware.cs. Next, write the following code inside this file.

public class SaveDataMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly IHostingEnvironment _hostingEnvironment;
        public SaveDataMiddleware(RequestDelegate next, IHostingEnvironment hostingEnvironment)
        {
            _next = next;
            _hostingEnvironment = hostingEnvironment;
        }
        public async Task Invoke(HttpContext httpContext)
        {
            bool isSaveDataEnabled = false;
            if (httpContext.Request.Headers.TryGetValue
             ("save-data", out StringValues saveDataHeaders))
            {
                isSaveDataEnabled = true;
            }
            if (isSaveDataEnabled)
            {
                //Write your custom code here
               // to send out optimized content
            }
            else
            {
               await _next(httpContext); //Save-Data not enabled
            }
        }      
    }

Add the Save-Data middleware to the request pipeline in ASP.Net Core

When building an ASP.Net Core application, you can draw on various middleware components to customize the handling of requests and responses, and even to inspect, route, or modify the request and response messages that flow through the pipeline.

Now that the custom middleware has been created, we must add it to the request processing pipeline. A middleware in ASP.Net Core is configured using the Configure method of the Startup class. The following code snippet shows how you can use an extension method on an instance of type IApplicationBuilder to add the middleware to the request processing pipeline.

public static class SaveDataRequestHeaderMiddlewareMiddlewareExtensions
{
    public static IApplicationBuilder UseSaveDataMiddleware(this IApplicationBuilder builder)
    {
        return builder.UseMiddleware<SaveDataRequestHeaderMiddleware>();
    }
}

Lastly, here is how you can use the extension method in the Configure method of the Startup class.

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            app.UseSaveDataMiddleware();
            app.UseMvc();
        }

And that is all you need to do. The custom middleware is now ready for use. Note that I have not written the code for optimizing the content—I will leave it up to you to write the necessary code to render optimized content if Save-Data is enabled.

The Save-Data header addresses the need to deliver optimized content at the client side. This header is used to let the server know that the client intends to reduce data usage. By detecting the Save-Data header in your ASP.Net Core application, you can accommodate the client by responding with lighter-weight content. 

joydip_kanjilal
Contributor

Joydip Kanjilal is a Microsoft Most Valuable Professional (MVP) in ASP.NET, as well as a speaker and the author of several books and articles. He received the prestigious MVP award for 2007, 2008, 2009, 2010, 2011, and 2012.

He has more than 20 years of experience in IT, with more than 16 years in Microsoft .Net and related technologies. He has been selected as MSDN Featured Developer of the Fortnight (MSDN) and as Community Credit Winner several times.

He is the author of eight books and more than 500 articles. Many of his articles have been featured at Microsoft’s Official Site on ASP.Net.

He was a speaker at the Spark IT 2010 event and at the Dr. Dobb’s Conference 2014 in Bangalore. He has also worked as a judge for the Jolt Awards at Dr. Dobb's Journal. He is a regular speaker at the SSWUG Virtual Conference, which is held twice each year.

More from this author