2024-07-05 01:35:19 +03:00
|
|
|
|
using Microsoft.AspNetCore.Http;
|
|
|
|
|
using System;
|
|
|
|
|
using System.Linq;
|
|
|
|
|
|
|
|
|
|
namespace Mirea.Api.Endpoint.Common.Services;
|
|
|
|
|
|
|
|
|
|
public static class UrlHelper
|
|
|
|
|
{
|
2024-11-04 02:35:43 +03:00
|
|
|
|
public static string GetCurrentScheme(this HttpContext context) =>
|
|
|
|
|
context.Request.Headers["X-Forwarded-Proto"].FirstOrDefault() ?? context.Request.Scheme;
|
|
|
|
|
|
2024-08-10 23:11:43 +03:00
|
|
|
|
public static string GetCurrentDomain(this HttpContext context) =>
|
2024-07-05 01:58:14 +03:00
|
|
|
|
context.Request.Headers["X-Forwarded-Host"].FirstOrDefault() ?? context.Request.Host.Host;
|
2024-12-23 06:56:01 +03:00
|
|
|
|
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()!);
|
2024-07-05 01:35:19 +03:00
|
|
|
|
|
|
|
|
|
private static string CreateSubPath(string? path)
|
|
|
|
|
{
|
|
|
|
|
if (string.IsNullOrEmpty(path))
|
|
|
|
|
return "/";
|
|
|
|
|
|
|
|
|
|
return "/" + path.Trim('/') + "/";
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public static string GetSubPath => CreateSubPath(Environment.GetEnvironmentVariable("ACTUAL_SUB_PATH"));
|
2024-07-05 01:59:36 +03:00
|
|
|
|
|
|
|
|
|
public static string GetSubPathWithoutFirstApiName
|
|
|
|
|
{
|
|
|
|
|
get
|
|
|
|
|
{
|
|
|
|
|
var path = GetSubPath;
|
|
|
|
|
|
|
|
|
|
if (string.IsNullOrEmpty(path) || path == "/")
|
|
|
|
|
return CreateSubPath(null);
|
|
|
|
|
|
|
|
|
|
var parts = path.Split('/', StringSplitOptions.RemoveEmptyEntries);
|
|
|
|
|
|
2024-11-04 02:34:50 +03:00
|
|
|
|
if (parts[^1].Equals("api", StringComparison.CurrentCultureIgnoreCase))
|
|
|
|
|
parts = parts.Take(parts.Length - 1).ToArray();
|
2024-07-05 01:59:36 +03:00
|
|
|
|
|
|
|
|
|
return CreateSubPath(string.Join("/", parts));
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2024-07-05 01:35:19 +03:00
|
|
|
|
public static string GetSubPathSwagger => CreateSubPath(Environment.GetEnvironmentVariable("SWAGGER_SUB_PATH"));
|
2024-11-04 02:35:43 +03:00
|
|
|
|
|
|
|
|
|
public static string GetApiUrl(this HttpContext context, string apiPath = "")
|
|
|
|
|
{
|
|
|
|
|
var scheme = GetCurrentScheme(context);
|
2024-12-18 07:29:05 +03:00
|
|
|
|
var domain = GetCurrentDomain(context).TrimEnd('/').Replace("localhost", "127.0.0.1");
|
2024-11-04 02:35:43 +03:00
|
|
|
|
|
2024-12-23 06:56:01 +03:00
|
|
|
|
var port = GetCurrentPort(context);
|
2024-11-04 02:35:43 +03:00
|
|
|
|
var portString = port.HasValue && port != 80 && port != 443 ? $":{port}" : string.Empty;
|
|
|
|
|
|
|
|
|
|
return $"{scheme}://{domain}{portString}{GetSubPathWithoutFirstApiName}{apiPath.Trim('/')}";
|
|
|
|
|
}
|
2024-07-05 01:35:19 +03:00
|
|
|
|
}
|