如何在反向代理后面获取应用程序基本 url

mir*_*zus 6 c# asp.net-mvc reverse-proxy urlhelper asp.net-web-api

有没有什么方法可以让 ASP.NET 应用程序能够在通过反向代理/网关的请求上下文中导出其 url 路径和主机名,了解其自己的路由?

通过网关请求此 url 时:

http://conoso.com/behind/some/reverseproxy/api/values/
Run Code Online (Sandbox Code Playgroud)

网关正在将请求重新路由到其他位置:

http://10.0.0.0/api/values
Run Code Online (Sandbox Code Playgroud)

它使用 DefaultApi 路由访问以下 ApiController ValuesController 的 Get 方法:

// GET api/values
public HttpResponseMessage Get()
{
  var res = Request.CreateResponse();
  res.Headers.Add(
    "Location",
    Url.Link(
      "DefaultApi",
      new
        {
          id = 1
        }));
  return res;
}
Run Code Online (Sandbox Code Playgroud)

它返回以下标头值:

Location: http://10.0.0.0/api/values/1
Run Code Online (Sandbox Code Playgroud)

虽然我希望发送以下有效路径:

Location: http://conoso.com/behind/some/reverseproxy/api/values/1
Run Code Online (Sandbox Code Playgroud)

使用框架中内置方法的替代方法是手动格式化字符串:

var baseUrl = "http://conoso.com/behind/some/reverseproxy";
string.Format("{0}/values/1", baseUrl);
Run Code Online (Sandbox Code Playgroud)

但这会散发出一些邪恶的代码味道。有人可以建议更清洁的方法吗?

mar*_*oss 1

我们的安全入口服务器也遇到了同样的问题。对于 REST 调用,我们希望在服务器端生成 url,以便它们在 java 脚本中可用。但它们不包括安全入口服务器添加的子路径。

因此我们想出了一个类似的解决方法(在布局页面中呈现):

<a id="urlBase" href="/" style="display: none;"></a>
<script type="text/javascript">
    baseUrl = document.getElementById('urlBase').getAttribute('href');
</script>
Run Code Online (Sandbox Code Playgroud)

href="/"已被入口服务器替换为href="/path/",我们可以baseUrl在访问 REST 服务时轻松连接相对路径。

希望它对您的情况也有帮助。

(我在这里发布了相同的答案,希望可以复制和粘贴)