Skip to content
Permalink
Browse files

Improve header handling, closes #2370

  • Loading branch information...
RicoSuter committed Aug 23, 2019
1 parent e05ef83 commit 8d3b67d9e9121424ee60030d52e7a76f080ad979
Showing with 15 additions and 16 deletions.
  1. +15 −16 src/NSwag.AspNetCore/HttpRequestExtension.cs
@@ -22,28 +22,22 @@ internal static class HttpRequestExtension
{
#if AspNetOwin
private static string GetHttpScheme(this IOwinRequest request)
{
return request.Headers["X-Forwarded-Proto"] ?? request.Scheme;
#else
private static string GetHttpScheme(this HttpRequest request)
{
return request.Headers["X-Forwarded-Proto"].FirstOrDefault() ?? request.Scheme;
#endif
{
return request.Headers.TryGetFirstHeader("X-Forwarded-Proto") ?? request.Scheme;
}

#if AspNetOwin
public static string GetServerUrl(this IOwinRequest request)
{
var baseUrl = request.Headers.ContainsKey("X-Forwarded-Host") ?
new Uri($"{request.GetHttpScheme()}://{request.Headers["X-Forwarded-Host"]}").ToString().TrimEnd('/') :
new Uri($"{request.GetHttpScheme()}://{request.Host}").ToString().TrimEnd('/');
#else
public static string GetServerUrl(this HttpRequest request)
#endif
{
var baseUrl = request.Headers.ContainsKey("X-Forwarded-Host") ?
new Uri($"{request.GetHttpScheme()}://{request.Headers["X-Forwarded-Host"].First()}").ToString().TrimEnd('/') :
new Uri($"{request.GetHttpScheme()}://{request.Headers.TryGetFirstHeader("X-Forwarded-Host")}").ToString().TrimEnd('/') :
new Uri($"{request.GetHttpScheme()}://{request.Host}").ToString().TrimEnd('/');
#endif

return $"{baseUrl}{request.GetBasePath()}".TrimEnd('/');
}
@@ -56,15 +50,11 @@ public static string GetBasePath(this HttpRequest request)
{
if (request.Headers.ContainsKey("X-Forwarded-Prefix"))
{
#if AspNetOwin
return "/" + request.Headers["X-Forwarded-Prefix"].Trim('/');
#else
return "/" + request.Headers["X-Forwarded-Prefix"].First().Trim('/');
#endif
return "/" + request.Headers.TryGetFirstHeader("X-Forwarded-Prefix").Trim('/');
}

var basePath = request.Headers.ContainsKey("X-Forwarded-Host") ?
new Uri($"http://{request.Headers["X-Forwarded-Host"].First()}").AbsolutePath :
new Uri($"http://{request.Headers.TryGetFirstHeader("X-Forwarded-Host")}").AbsolutePath :
"";

if (request.PathBase.HasValue)
@@ -74,5 +64,14 @@ public static string GetBasePath(this HttpRequest request)

return ("/" + basePath.Trim('/')).TrimEnd('/');
}

private static string TryGetFirstHeader(this IHeaderDictionary headers, string name)
{
#if AspNetOwin
return headers[name]?.Split(',').Select(s => s.Trim()).First();
#else
return headers[name].FirstOrDefault()?.Split(',').Select(s => s.Trim()).First();
#endif
}
}
}

0 comments on commit 8d3b67d

Please sign in to comment.
You can’t perform that action at this time.