80 lines
3.5 KiB
C#
80 lines
3.5 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";
|
|
|
|
// Skip if this is already an internal area/controller name (starts with capital letter)
|
|
if (char.IsUpper(translatedArea[0]) || char.IsUpper(translatedController[0]))
|
|
{
|
|
_logger.LogInformation($"Skipping internal path: {path}");
|
|
await _next(context);
|
|
return;
|
|
}
|
|
|
|
_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);
|
|
}
|
|
}
|
|
} |