So I had a requirement to inject a HTTP Header into a web request, detect it server-side and either include or omit code depending on the value of the header.
We wanted to use it as a way to signal if the server should activate or deactivate a control, using a single location to control it, across multiple URL’s, which must be hidden to the end user. We couldn’t use a config file or the usual things like App Config, URL parameters or on Page items, so we decided to inject HTTP Headers via our infrastructure.
As it stands using Cloudflare is quite easy to accomplish this.
The Solution
Inject the header
Within Cloudflare, add a HTTP Request Rule
Detect the header
Within the code, detect the newly injected header like so:
@{
bool isHeaderDetected = false;
bool.TryParse(Request.Headers["X-MyNewHeader"], out isHeaderDetected);
}
@if (isHeaderDetected)
{
// We have a header - add what we need to add / omit what we need to omit
}
else
{
// We don't have a header - add what we need to add / omit what we need to omit
}
Testing
Testing it locally is a little more tricky, as you need the code running locally but can’t use Cloudflare to inject the header.
So the trick I came up with was to use a free product called Fiddler from Telerik.
Download Fiddler from the Telerik website.
Once downloaded, install it by running the .exe file.
Open Fiddler, you will be prompted with a dialog asking if you want to learn more about App Containers, select Cancel
to disable this.
On the AutoResponder
Tab.
Put a tick in the checkboxs Enable rules
and Unmatched requests pass through
Select Add Rule
to ad a new rule entry.
In the field If request matches
add the condition for the requests you want to modify.
e.g.
You can use a regular expression to match URLs.
regex:(?insx).*
will match all incoming requests, use the drop down on this field to explore more options
Then in the then respond with
field, select *header
from the drop down list and then specify the header you want to inject.
e.g.
*header X-MyNewHeader: true
Click the Save
button and then put a tick in the box to Enable
the Rule
This rule will inject the X-MyNewHeader
with the value true
into all requests matching the specified URL pattern.
Feel free to adjust the conditions and headers / values to suit your specific needs.