using System.Globalization; namespace OliverBooth.Middleware; /// /// Redirects requests to the default culture if the culture is not specified in the URL. /// internal sealed class CultureRedirectMiddleware { private readonly RequestDelegate _next; /// /// Initializes a new instance of the class. /// /// The next request delegate. public CultureRedirectMiddleware(RequestDelegate next) { _next = next; } /// /// Invokes the middleware. /// /// The HTTP context. public async Task Invoke(HttpContext context) { const StringComparison comparison = StringComparison.OrdinalIgnoreCase; HttpRequest request = context.Request; PathString requestPath = request.Path; if (requestPath.HasValue) { string[] pathSegments = requestPath.Value.Split('/'); CultureInfo[] cultures = CultureInfo.GetCultures(CultureTypes.AllCultures); if (pathSegments.Length >= 2 && cultures.Any(CultureMatch)) { await _next(context); return; } bool CultureMatch(CultureInfo culture) { string segment = pathSegments[1].Split('-')[0]; return string.Equals(culture.TwoLetterISOLanguageName, segment, comparison); } } const string defaultCulture = "en"; var redirectUrl = $"/{defaultCulture}{requestPath}{request.QueryString}"; context.Response.Redirect(redirectUrl); } }