Message Handler to Filter Network Requests – C# examples

Using message handlers is a typical pattern in software development. Message handlers are used to intercept and process messages in a pipeline manner. In this article, we will create custom message handlers that filters network requests and disables unwanted ones. You find simple C# examples of how to apply message handlers for network operations.

Network Requests

In software engineering, network requests refer to a client application sending a request to a server over the network and receiving a response from the server. Message handlers are a powerful way to intercept and process these network requests and responses.
This article considers examples of intercepting requests, blocking some unwanted network requests, or replacing the URLs with some other value.

Message Handler to Filter Network Requests

Aspose.HTML for .NET library provides functionality that can be useful in scenarios where you want to restrict certain types of network requests in an HTML processing application. For example, if you work with HTML documents and want to ensure that only certain types of resources are loaded from external sources. This code provides a way to filter out undesired network requests, in this case – exclude files and base64-encoded data.

Let’s look at the C# code snippet that uses the Aspose.HTML library to work with HTML documents and network operations. This code sets up the NetworkDisabledMessageHandler that filters out network requests with “file:” or “base64:” protocols and lets other requests pass through.

 1using System;
 2using Aspose.Html.Net;
 3...
 4
 5	// Define the NetworkDisabledMessageHandler class that is derived from the MessageHandler class
 6    public class NetworkDisabledMessageHandler : MessageHandler
 7    {
 8        // Override the Invoke() method
 9        public override void Invoke(INetworkOperationContext context)
10        {
11            if (context.Request.RequestUri.Protocol == "file:" || context.Request.RequestUri.Protocol == "base64:")
12                Next(context);
13        }
14    }

The above C# code snippet creates a message handler to customize the behavior of network requests based on their protocols:

This custom message handler can filter out network requests in your .NET project or application.

How to Filter out Undesired Network Requests

Here is an example of how you can use the NetworkDisabledMessageHandler class to filter out undesired network requests using the Aspose.HTML library:

  1. Create an instance of the Configuration class using Configuration() constructor.
  2. Call the GetService<INetworkService>() method on the configuration object to retrieve an instance of the INetworkService interface.
  3. Use the Insert() method to add the message handler to the top of existing message handler chain. This means that any network requests made through INetworkService will first pass through NetworkDisabledMessageHandler.
  4. Create an instance of the HTMLDocument class, passing to it the path to the HTML file and the configuration object.
 1using Aspose.Html;
 2using Aspose.Html.Net;
 3using Aspose.Html.Services;
 4using System.IO;
 5...
 6
 7    // Create an instance of the Configuration class
 8    using var configuration = new Configuration();
 9
10    // Call the INetworkService which contains the functionality for managing network operations
11    var network = configuration.GetService<INetworkService>();
12
13    // Add the TimeoutMessageHandler to the top of existing message handler chain
14    network.MessageHandlers.Insert(0, new NetworkDisabledMessageHandler());
15
16    // Prepare path to a source document file
17    string documentPath = Path.Combine(DataDir, "document.html");
18
19    // Create an HTML document with a custom configuration
20    using var document = new HTMLDocument(documentPath, configuration);

Message Handler to Block External Network Requests

Look at the C# example that creates the NetworkChangeMessageHandler that blocks all external network requests and changes their URLs to local. This message handler can be used in development environment testing or in scenarios where certain types of external resources need to be blocked or redirected for security, etc.

 1using System;
 2using Aspose.Html.Net;
 3...
 4
 5	// Define the NetworkChangeMessageHandler class that is derived from the MessageHandler class
 6    public class NetworkChangeMessageHandler : MessageHandler
 7    {
 8        // Override the Invoke() method
 9        public override void Invoke(INetworkOperationContext context)
10        {
11            if (context.Request.RequestUri.Protocol == "file:" || context.Request.RequestUri.Protocol == "base64:")
12            {
13                Next(context);
14                return;
15            }
16
17            context.Request.RequestUri = new Url(context.Request.RequestUri.Pathname, "http://localhost:8080");
18        }
19    }

The created NetworkChangeMessageHandler class is a custom message handler that intercepts network requests and modifies the request URI based on specific conditions:

This is essentially the use of a message handler to provide work in isolated environments and block external network requests because the handler skips only local resources such as files and base64-encoded data, and it changes all external URLs to local ones.

 1using Aspose.Html;
 2using Aspose.Html.Net;
 3using Aspose.Html.Services;
 4using System.IO;
 5...
 6
 7	// Create an instance of the Configuration class
 8    using var configuration = new Configuration();
 9
10    // Call the INetworkService which contains the functionality for managing network operations
11    var network = configuration.GetService<INetworkService>();
12
13    // Add the CustomNetworkMessageHandler to the top of existing message handler chain
14    network.MessageHandlers.Insert(0, new NetworkChangeMessageHandler());
15
16    // Create an HTML document with a custom configuration
17    using var document = new HTMLDocument("https://products.aspose.com/html/", configuration);

When an HTMLDocument is created using the Configuration class object, any network requests made on the HTMLDocument instance will first go through the NetworkChangeMessageHandler. The message handler changes the URL and redirects external network requests to the “localhost.”

You can download the complete examples and data files from GitHub.

Subscribe to Aspose Product Updates

Get monthly newsletters & offers directly delivered to your mailbox.