68 lines
1.9 KiB
C#
68 lines
1.9 KiB
C#
using Microsoft.AspNetCore.Http;
|
|
using Microsoft.Extensions.Primitives;
|
|
using System;
|
|
using System.Linq;
|
|
|
|
namespace Kit.Helpers
|
|
{
|
|
public static class HttpContextCore
|
|
{
|
|
private static IServiceProvider _serviceProvider;
|
|
private static bool _notWebApp;
|
|
|
|
public static void Configure(IServiceProvider serviceProvider)
|
|
{
|
|
_serviceProvider = serviceProvider;
|
|
_notWebApp = false;
|
|
}
|
|
|
|
public static void ConfigureNotWebApp()
|
|
{
|
|
_notWebApp = true;
|
|
}
|
|
|
|
public static HttpContext Current
|
|
{
|
|
get
|
|
{
|
|
if (_notWebApp)
|
|
{
|
|
return null;
|
|
}
|
|
object factory = _serviceProvider.GetService(typeof(IHttpContextAccessor));
|
|
|
|
HttpContext context = ((HttpContextAccessor)factory).HttpContext;
|
|
|
|
return context;
|
|
}
|
|
}
|
|
|
|
private static readonly string _contextHostUrl = "HostUrl";
|
|
|
|
public static string GetHostUrl(this HttpContext context)
|
|
{
|
|
context.Items[_contextHostUrl] = context.Items[_contextHostUrl] as string ?? context.GenerateHostUrl();
|
|
return context.Items[_contextHostUrl]!.ToString()!;
|
|
}
|
|
|
|
public static string GetRootUrl(this HttpContext context)
|
|
{
|
|
return $"{GetHostUrl(context)}{context.Request.PathBase}{context.Request.Path}";
|
|
}
|
|
|
|
private static string GenerateHostUrl(this HttpContext context)
|
|
{
|
|
HttpRequest request = context.Request;
|
|
|
|
// Формируем RootUrl
|
|
string scheme = request.Scheme;
|
|
|
|
if (request.Headers.TryGetValue("X-Forwarded-Proto", out StringValues forwardedProtoValues) && forwardedProtoValues.Count > 0)
|
|
{
|
|
scheme = forwardedProtoValues.First();
|
|
}
|
|
|
|
return $"{scheme}://{request.Host}";
|
|
}
|
|
}
|
|
} |