Proxy example for Optimizely CMS with ASP.NET and C#

Add the custom settings object

To start using proxied requests and avoid a direct browser connection to Rek.ai, add this custom settings object to all pages, with your local endpoints configured:

<script>
    window.rek_customsettings = window.rek_customsettings || {};
    window.rek_customsettings.proxypredict = '/rest-api/rek/proxypredict';
    window.rek_customsettings.proxyview = '/rest-api/rek/proxyview';
</script>

Register named HttpClients

Register new named HttpClients in Startup.cs and ConfigureServices(IServiceCollection services), or the equivalent in Program.cs if you have migrated to it:

const string RekPredictBaseAddress = "https://predict.rekai.se";
const string RekViewBaseAddress = "https://view.rekai.se";
const string RekStaticBaseAddress = "https://static.rekai.se";
 
services.AddHttpClient("RekProxyPredict", httpClient =>
    {
        httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        httpClient.BaseAddress = new Uri(RekPredictBaseAddress);
        httpClient.Timeout = TimeSpan.FromSeconds(5);
    })
    .ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler
    {
        AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate | DecompressionMethods.Brotli,
        AllowAutoRedirect = false,
        UseCookies = false,
    });
 
services.AddHttpClient("RekProxyView", httpClient =>
    {
        httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        httpClient.BaseAddress = new Uri(RekViewBaseAddress);
        httpClient.Timeout = TimeSpan.FromSeconds(5);
    })
    .ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler
    {
        AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate | DecompressionMethods.Brotli,
        AllowAutoRedirect = false,
        UseCookies = false,
    });
 
services.AddHttpClient("RekProxyStatic", httpClient =>
    {
        httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/html"));
        httpClient.BaseAddress = new Uri(RekStaticBaseAddress);
        httpClient.Timeout = TimeSpan.FromSeconds(5);
    })
    .ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler
    {
        AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate | DecompressionMethods.Brotli,
        AllowAutoRedirect = false,
        UseCookies = false,
    });

Forward request headers

Add this static method at the end of Startup.cs:

// Handles which headers to forward, change or remove before sending request to Rek.ai
private static void AddRekProxyRequestHeaders(HttpContext context, HttpRequestMessage message)
{
    if (context.Request.Headers.UserAgent.Count > 0)
    {
        message.Headers.TryAddWithoutValidation("User-Agent", context.Request.Headers.UserAgent.ToString());
    }
 
    if (context.Request.Headers.Origin.Count > 0)
    {
        message.Headers.TryAddWithoutValidation("Origin", context.Request.Headers.Origin.ToString());
    }
 
    if (context.Request.Headers.Referer.Count > 0)
    {
        message.Headers.TryAddWithoutValidation("Referer", context.Request.Headers.Referer.ToString());
    }
}

Add the proxy endpoints

Now you're ready to add the two endpoints that handle the proxy calls. In this example, place them inside app.UseEndpoints(endpoints => ...):

using Microsoft.AspNetCore.WebUtilities;
..
endpoints.MapGet("/rest-api/rek/{*remainder}", async (string remainder, IHttpClientFactory httpClientFactory, HttpContext context) =>
    {
        var queryString = context.Request.QueryString.Value ?? string.Empty;
 
        var queryValues = QueryHelpers.ParseQuery(queryString);
 
        // Add secret key parameter to back-channel URL
        // Here you can also add, change or remove other querystring parameters
        queryValues["srek"] = siteSettings.RekSecretKey;
 
        var predictUrl = QueryHelpers.AddQueryString($"https://predict.rekai.se/{remainder?.Replace("proxypredict", "predict").TrimStart('/')}", queryValues);
 
        using var message = new HttpRequestMessage(HttpMethod.Get, predictUrl);
 
        AddRekProxyRequestHeaders(context, message);
 
        // Forward the request to Rek.ai
        var httpClient = httpClientFactory.CreateClient("RekProxyPredict");
        using var response = await httpClient.SendAsync(
            message,
            HttpCompletionOption.ResponseHeadersRead,
            context.RequestAborted).ConfigureAwait(false);
 
        context.Response.StatusCode = (int)response.StatusCode;
        context.Response.ContentType = response.Content.Headers.ContentType?.ToString() ?? "application/json";
 
        // Copy content to your response
        await using var responseStream = await response.Content.ReadAsStreamAsync(context.RequestAborted).ConfigureAwait(false);
        await responseStream.CopyToAsync(context.Response.Body, context.RequestAborted).ConfigureAwait(false);
 
        return Results.Empty;
    });
 
endpoints.MapPost("/rest-api/rek/{*remainder}", async (string remainder, IHttpClientFactory httpClientFactory, HttpContext context) =>
    {
        using var message = new HttpRequestMessage(HttpMethod.Post, $"https://view.rekai.se/{remainder?.Replace("proxyview", "view").TrimStart('/')}");
 
        AddRekProxyRequestHeaders(context, message);
 
        // Read the request body into a changeable object
        JsonNode jsonNode;
 
        try
        {
            jsonNode = await JsonNode.ParseAsync(context.Request.Body, cancellationToken: context.RequestAborted).ConfigureAwait(false);
        }
        catch (JsonException)
        {
            return Results.BadRequest("Invalid JSON payload.");
        }
 
        if (jsonNode is null)
        {
            return Results.BadRequest("Request body cannot be empty.");
        }
 
        // Add secret key parameter to back-channel JSON body
        jsonNode["srek"] = siteSettings.RekSecretKey;
 
        // Set changed JSON to the request about to be forwarded
        message.Content = JsonContent.Create(jsonNode);
 
        // Forward the request to Rek.ai
        var httpClient = httpClientFactory.CreateClient("RekProxyView");
        using var response = await httpClient.SendAsync(
            message,
            HttpCompletionOption.ResponseHeadersRead,
            context.RequestAborted).ConfigureAwait(false);
 
        context.Response.StatusCode = (int)response.StatusCode;
        context.Response.ContentType = response.Content.Headers.ContentType?.ToString() ?? "application/json";
 
        // Copy content to your response
        await using var responseStream = await response.Content.ReadAsStreamAsync(context.RequestAborted).ConfigureAwait(false);
        await responseStream.CopyToAsync(context.Response.Body, context.RequestAborted).ConfigureAwait(false);
 
        return Results.Empty;
    });
 
endpoints.MapGet("/static/rek/{*remainder}", async (string remainder, IHttpClientFactory httpClientFactory, HttpContext context) =>
    {
        using var message = new HttpRequestMessage(HttpMethod.Get, "https://static.rekai.se/" + remainder?.TrimStart('/'));
 
        AddRekProxyRequestHeaders(context, message);
 
        // Forward the request to Rek.ai
        var httpClient = httpClientFactory.CreateClient("RekProxyStatic");
        using var response = await httpClient.SendAsync(
            message,
            HttpCompletionOption.ResponseHeadersRead,
            context.RequestAborted).ConfigureAwait(false);
 
        context.Response.StatusCode = (int)response.StatusCode;
 
        foreach (var header in response.Headers)
        {
            if (header.Key.Equals("Cache-Control", StringComparison.OrdinalIgnoreCase)
                || header.Key.Equals("Date", StringComparison.OrdinalIgnoreCase)
                || header.Key.Equals("ETag", StringComparison.OrdinalIgnoreCase)
                || header.Key.Equals("Expires", StringComparison.OrdinalIgnoreCase)
                || header.Key.Equals("Last-Modified", StringComparison.OrdinalIgnoreCase))
            {
                context.Response.Headers[header.Key] = new StringValues(header.Value.ToArray());
            }
        }
 
        // Based on file extension - get the Content-Type your runtime wants to use
        var contentTypeProvider = new FileExtensionContentTypeProvider();
        if (!contentTypeProvider.TryGetContentType(remainder, out var contentType))
        {
            contentType = response.Content.Headers.ContentType?.ToString() ?? "application/octet-stream";
        }
 
        context.Response.ContentType = contentType;
 
        // Copy content to your response
        await using var responseStream = await response.Content.ReadAsStreamAsync(context.RequestAborted).ConfigureAwait(false);
        await responseStream.CopyToAsync(context.Response.Body, context.RequestAborted).ConfigureAwait(false);
 
        return Results.Empty;
    });

Proxy static files

If you also want to proxy and serve static files from your domain you can adjust script and CSS references, with the code the above this will be the local URLs:

  • /static/rek/YOUR_SCRIPT_ID.js
  • /static/rek/files/rekai-styles.css
  • /static/rek/addon/rekai_autocomplete.min.js

It's recommended to have these endpoints cached. The response headers and file extensions should cache automatically with Optimizely DXP's Cloudflare CDN configuration.

Optional additions