Skip to content

Commit f63afbf

Browse files
Added UpstreamHost placeholder to identify host from which request origination
1 parent 347ea72 commit f63afbf

File tree

2 files changed

+36
-1
lines changed

2 files changed

+36
-1
lines changed

src/Ocelot/Infrastructure/Placeholders.cs

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ namespace Ocelot.Infrastructure
77
using Ocelot.Responses;
88
using System;
99
using System.Collections.Generic;
10+
using System.Linq;
1011

1112
public class Placeholders : IPlaceholders
1213
{
@@ -25,7 +26,8 @@ public Placeholders(IBaseUrlFinder finder, IRequestScopedDataRepository repo, IH
2526
{
2627
{ "{BaseUrl}", GetBaseUrl() },
2728
{ "{TraceId}", GetTraceId() },
28-
{ "{RemoteIpAddress}", GetRemoteIpAddress() }
29+
{ "{RemoteIpAddress}", GetRemoteIpAddress() },
30+
{ "{UpstreamHost}", GetUpstreamHost() },
2931
};
3032

3133
_requestPlaceholders = new Dictionary<string, Func<DownstreamRequest, string>>
@@ -130,5 +132,27 @@ private Func<Response<string>> GetBaseUrl()
130132
{
131133
return () => new OkResponse<string>(_finder.Find());
132134
}
135+
136+
private Func<Response<string>> GetUpstreamHost()
137+
{
138+
return () =>
139+
{
140+
try
141+
{
142+
if (_httpContextAccessor.HttpContext.Request.Headers.TryGetValue("Host", out var upstreamHost))
143+
{
144+
return new OkResponse<string>(upstreamHost.First());
145+
}
146+
else
147+
{
148+
return new ErrorResponse<string>(new CouldNotFindPlaceholderError("{UpstreamHost}"));
149+
}
150+
}
151+
catch
152+
{
153+
return new ErrorResponse<string>(new CouldNotFindPlaceholderError("{UpstreamHost}"));
154+
}
155+
};
156+
}
133157
}
134158
}

test/Ocelot.UnitTests/Infrastructure/PlaceholdersTests.cs

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -123,5 +123,16 @@ public void should_return_error_when_removed()
123123
result.IsError.ShouldBeTrue();
124124
result.Errors[0].Message.ShouldBe("Unable to remove placeholder: {Test}, placeholder does not exists");
125125
}
126+
127+
[Fact]
128+
public void should_return_upstreamHost()
129+
{
130+
var upstreamHost = "UpstreamHostA";
131+
var httpContext = new DefaultHttpContext();
132+
httpContext.Request.Headers.Add("Host", upstreamHost);
133+
_accessor.Setup(x => x.HttpContext).Returns(httpContext);
134+
var result = _placeholders.Get("{UpstreamHost}");
135+
result.Data.ShouldBe(upstreamHost);
136+
}
126137
}
127138
}

0 commit comments

Comments
 (0)