ocelot在部署時我使用了nginx作為轉發,並配置了https證書,但是發現ocelot不支持Forward host header。
https://ocelot.readthedocs.io/en/latest/introduction/notsupported.html
這時候我就有了個疑問,Forward host header到底時什么含義?於是便有了本文。
nginx等代理服務器在轉發時,會使用X-Forwarded-For 請求頭。該請求頭會記錄從請求者ip到層層代理服務器ip的信息。
https://imququ.com/post/x-forwarded-for-header-in-http.html
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-For
asp.net core 在使用轉發服務器后,官方文檔說需要使用中間件設置XForwardedFor與XForwardedProto
https://docs.microsoft.com/en-us/aspnet/core/fundamentals/servers/kestrel?view=aspnetcore-2.2#when-to-use-kestrel-with-a-reverse-proxy
app.UseForwardedHeaders(new ForwardedHeadersOptions
{
ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
});
app.UseAuthentication();
使用X-Forwarded-For會更新 HttpContext.Connection.RemoteIpAddress
使用X-Forwarded-Proto會更新 HttpContext.Request.Scheme
使用X-Forwarded-Host會更新 HttpContext.Request.Host
https://docs.microsoft.com/en-us/aspnet/core/host-and-deploy/proxy-load-balancer?view=aspnetcore-2.2
我建立了一些測試的webapi來查看效果
[HttpGet]
public ActionResult<IEnumerable<string>> Get()
{
var remoteIp = HttpContext.Connection.RemoteIpAddress;
string ip = remoteIp.MapToIPv4().ToString();
var scheme = HttpContext.Request.Scheme;
string sch = scheme.ToString();
var host = HttpContext.Request.Host;
string ho = host.ToString();
return new string[] { ip,sch,ho };
}
是否使用中間件,會影響到http和RemoteIPAddress的值是否正確。
而使用了ocelot轉發api后,無法讀取到host的正確值。ocelot無需添加中間件 ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
如果添加了,反而會無法獲取到正確的remoteip以及scheme