Handling Redirects with Middleware in .Net

Handling Redirects with Middleware in .Net

Calculating...

I had a need to do a load of redirects when migrating a site from one platform to Umbraco 13. 

Here is how I handled the issue by using middleware and a csv file. 

The CSV file was created by a client and would be updated / maintained by them so it made sense to use that as the "source of truth". 

The CSV file looks a bit like this : 

/old-page,/new-page
/another-old-page,/another-new-page

The CSV file is saved on the root of my solution for ease of access.

The Middleware code, which is saved in a file called RedirectMiddleware.cs looks like this:

namespace MySite.Web.Infrastructure.Middleware
{
    public class RedirectMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly Serilog.ILogger _logger;
        private readonly Dictionary<string, string> _redirects;

        public RedirectMiddleware(RequestDelegate next, Serilog.ILogger logger)
        {
            _next = next;
            _logger = logger;
            _redirects = LoadRedirects();
        }

        public async Task InvokeAsync(HttpContext context)
        {
            if (_redirects.TryGetValue(context.Request.Path.Value, out var targetUrl))
            {
                _logger.Information($"Redirecting from {context.Request.Path} to {targetUrl}");
                context.Response.Redirect(targetUrl, true);
                return;
            }

            await _next(context);
        }

        private Dictionary<string, string> LoadRedirects()
        {
            var redirects = new Dictionary<string, string>();
            var filePath = Path.Combine(Directory.GetCurrentDirectory(), "redirects.csv");

            if (File.Exists(filePath))
            {
                var lines = File.ReadAllLines(filePath);
                foreach (var line in lines)
                {
                    var parts = line.Split(',');
                    if (parts.Length == 2)
                    {
                        redirects[parts[0].Trim()] = parts[1].Trim();
                    }
                }
            }

            return redirects;
        }
    }
}

and then in my Startup.cs or Program.cs I just added the Middleware like :

app.UseMiddleware<RedirectMiddleware>();

And that is it. When I hit /old-page I am redirected to /new-page (as long as it exists, if it doesn't then I will still get a 404 error.

One thing to note, this is using Serilog.ILogger as it's within an Umbraco 13 site and this allows me to save to the log files within Umbraco.