Polianin Nikita 053f01eec1
All checks were successful
.NET Test Pipeline / build-and-test (push) Successful in 1m33s
Build and Deploy Docker Container / build-and-deploy (push) Successful in 1m35s
fix: hotfix getting current port
2024-12-23 06:56:01 +03:00

58 lines
2.1 KiB
C#

using Microsoft.AspNetCore.Http;
using System;
using System.Linq;
namespace Mirea.Api.Endpoint.Common.Services;
public static class UrlHelper
{
public static string GetCurrentScheme(this HttpContext context) =>
context.Request.Headers["X-Forwarded-Proto"].FirstOrDefault() ?? context.Request.Scheme;
public static string GetCurrentDomain(this HttpContext context) =>
context.Request.Headers["X-Forwarded-Host"].FirstOrDefault() ?? context.Request.Host.Host;
public static int? GetCurrentPort(this HttpContext context) =>
string.IsNullOrEmpty(context.Request.Headers["X-Forwarded-Port"].FirstOrDefault()) ? context.Request.Host.Port :
int.Parse(context.Request.Headers["X-Forwarded-Port"].First()!);
private static string CreateSubPath(string? path)
{
if (string.IsNullOrEmpty(path))
return "/";
return "/" + path.Trim('/') + "/";
}
public static string GetSubPath => CreateSubPath(Environment.GetEnvironmentVariable("ACTUAL_SUB_PATH"));
public static string GetSubPathWithoutFirstApiName
{
get
{
var path = GetSubPath;
if (string.IsNullOrEmpty(path) || path == "/")
return CreateSubPath(null);
var parts = path.Split('/', StringSplitOptions.RemoveEmptyEntries);
if (parts[^1].Equals("api", StringComparison.CurrentCultureIgnoreCase))
parts = parts.Take(parts.Length - 1).ToArray();
return CreateSubPath(string.Join("/", parts));
}
}
public static string GetSubPathSwagger => CreateSubPath(Environment.GetEnvironmentVariable("SWAGGER_SUB_PATH"));
public static string GetApiUrl(this HttpContext context, string apiPath = "")
{
var scheme = GetCurrentScheme(context);
var domain = GetCurrentDomain(context).TrimEnd('/').Replace("localhost", "127.0.0.1");
var port = GetCurrentPort(context);
var portString = port.HasValue && port != 80 && port != 443 ? $":{port}" : string.Empty;
return $"{scheme}://{domain}{portString}{GetSubPathWithoutFirstApiName}{apiPath.Trim('/')}";
}
}