如何解决如何在 .core 中更改 Swagger 的基本 url 取决于请求
在旧版本的 Swagger(.Net 框架)中,我使用此函数更改 URL:
async function importRecord() {
let records = [...]
let batch = db.batch()
for(let record in records) {
if (batch.ops.length >= 500) {
await batch.commit();
batch = db.batch();
}
createRecord(db,batch)
}
if(batch.ops.length > 0) {
await batch.commit()
}
}
function createRecord(db,batch) {
batch.update(...)
}
实际上我从请求中计算出基本 URL(我的应用在负载均衡器后面)
新的 .core 方法是使用这个 RootUrl(req => ComputeHostAsSeenByOriginalClient(req))
问题:
RoutePrefix 是 Property 而不是 Action,所以我没有 RoutePrefix
这是HttpRequestMessage
的完整代码:
ComputeHostAsSeenByOriginalClient
知道如何解决这个问题吗?
解决方法
尝试使用 this.Request
。您可以从 Controller
访问请求对象。
public string ComputeHostAsSeenByOriginalClient()
{
var req = this.Request;
var scheme = req.Scheme;
var authority = this.Request.Host.Value.ToString();
if (req.Headers.ContainsKey("X-Forwarded-Host"))
{
//we are behind a reverse proxy,use the host that was used by the client
StringValues xForwardedHost = "";
if (req.Headers.TryGetValue("X-Forwarded-Host",out xForwardedHost))
{
//when multiple apache httpd are chained,each proxy append to the header
//with a comma (see //https://httpd.apache.org/docs/2.4/mod/mod_proxy.html#x-headers).
//so we need to take only the first host because it is the host that was
//requested by the original client.
//note that other reverse proxies may behave differently but
//we are not taking care of them...
var firstForwardedHost = xForwardedHost.First().ToString().Split(',')[0];
authority = firstForwardedHost;
}
}
if (req.Headers.ContainsKey("X-Forwarded-Proto"))
{
//now that we have the host,we also need to determine the protocol used by the
//original client.
//if present,we are using the de facto standard header X-Forwarded-Proto
//otherwise,we fallback to http
//note that this is extremely brittle,either because the first proxy
//can "forget" to set the header or because another proxy can rewrite it...
StringValues xForwardedProto = "";
if (req.Headers.TryGetValue("X-Forwarded-Proto",out xForwardedProto))
{
if (xForwardedProto.First().ToString().IndexOf(",") != -1)
{
//when multiple apache,X-Forwarded-Proto is also multiple ...
xForwardedProto = xForwardedProto.First().ToString().Split(',')[0];
}
scheme = xForwardedProto;
}
}
//no reverse proxy mean we can directly use the RequestUri
return scheme + "://" + authority;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。