Convert-it/Middleware/UrlTranslationMiddleware.cs
Ricardo Carneiro be3a93f90d
Some checks failed
Deploy ASP.NET MVC to OCI / build-and-deploy (push) Has been cancelled
fix: ajustes de idioma e pipelina
2025-09-12 13:45:37 -03:00

72 lines
3.2 KiB
C#

using Convert_It_Online.Services;
using System.Globalization;
using System.Text.RegularExpressions;
namespace Convert_It_Online.Middleware
{
public class UrlTranslationMiddleware
{
private readonly RequestDelegate _next;
private readonly IUrlTranslationService _urlTranslationService;
private readonly ILogger<UrlTranslationMiddleware> _logger;
public UrlTranslationMiddleware(RequestDelegate next, IUrlTranslationService urlTranslationService, ILogger<UrlTranslationMiddleware> logger)
{
_next = next;
_urlTranslationService = urlTranslationService;
_logger = logger;
}
public async Task InvokeAsync(HttpContext context)
{
var path = context.Request.Path.Value;
if (!string.IsNullOrEmpty(path))
{
_logger.LogInformation($"Processing path: {path}");
// Pattern: /{culture}/{translatedArea}/{translatedController}[/{action}]
var match = Regex.Match(path, @"^/([a-z]{2}-[A-Z]{2})/([^/]+)/([^/]+)(?:/([^/]+))?");
if (match.Success)
{
var cultureName = match.Groups[1].Value;
var translatedArea = match.Groups[2].Value;
var translatedController = match.Groups[3].Value;
var action = match.Groups[4].Success ? match.Groups[4].Value : "Index";
_logger.LogInformation($"Matched: culture={cultureName}, area={translatedArea}, controller={translatedController}, action={action}");
try
{
var culture = new CultureInfo(cultureName);
var originalArea = _urlTranslationService.GetOriginalArea(translatedArea, culture);
var originalController = _urlTranslationService.GetOriginalController(translatedController, culture);
_logger.LogInformation($"Translations: originalArea={originalArea}, originalController={originalController}");
if (originalArea != null && originalController != null)
{
// Rewrite the path to use original controller names
var newPath = $"/{cultureName}/{originalArea}/{originalController}";
if (!string.IsNullOrEmpty(action) && action != "Index")
{
newPath += $"/{action}";
}
_logger.LogInformation($"Rewriting path from {path} to {newPath}");
context.Request.Path = newPath;
}
}
catch (CultureNotFoundException)
{
_logger.LogWarning($"Culture {cultureName} not found");
// Continue with original path if culture is not supported
}
}
}
await _next(context);
}
}
}