[译]Ocelot - Headers Transformation

原文

Add to Request

为上游请求添加请求头,只需如下一样将下面的配置添加到一个ReRoute里:

"UpstreamHeaderTransform": {
    "Uncle": "Bob"
}

上面的例子中添加了一个键为Uncle,值为Bob的请求头。

支持Placeholders。

Add to Response

还可以为下游服务添加响应头, 如下一样将下面的配置添加到一个ReRoute里:

"DownstreamHeaderTransform": {
    "Uncle": "Bob"
},

如果你想返回Butterfly APM trace id,可以如下配置:

"DownstreamHeaderTransform": {
    "AnyKey": "{TraceId}"
},

Find and Replace

为了transform一个http头,我们需要指定一个http头的键,然后入下一样设置transform:

"Test": "http://www.bbc.co.uk/, http://ocelot.com/"

键是“Test”, 值是“http://www.bbc.co.uk/, http://ocelot.com/”。这个值得意思是将 http://www.bbc.co.uk/ 替换成 http://ocelot.com/。相应的语法是:{find}, {replace}。

Pre Downstream Request

下面的位于一个ReRoute的配置会将 http://www.bbc.co.uk/ 替换成 http://ocelot.com/。 这个请求头在请求下游的时候会被修改,然后再发送至下游服务器。

 "UpstreamHeaderTransform": {
    "Test": "http://www.bbc.co.uk/, http://ocelot.com/"
}

Post Downstream Request

下面的位于一个ReRoute的配置会将 http://www.bbc.co.uk/ 替换成 http://ocelot.com/。ocelot在收到下游服务器的响应的时候回将替换掉响应的http响应头。

"DownstreamHeaderTransform": {
    "Test": "http://www.bbc.co.uk/, http://ocelot.com/"
},

Placeholders

header transformation支持placeholder。

  • {BaseUrl} - 这个使用的是Ocelot的base url。例如值为:http://localhost:5000
  • {DownstreamBaseUrl} - 这个使用的是下游服务的base url。例如值为:http://localhost:5000。这个只有在DownstreamHeaderTransform里面才有效
  • {TraceId} - 这个使用的是 Butterfly APM Trace Id。这个只有在DownstreamHeaderTransform里面才有效

Handling 302 Redirects

Ocelot默认是自动根据响应头里面的Location自动跳转的。如果你想将响应头里面的location返回给客户,可以如下一样配置。

"DownstreamHeaderTransform": {
    "Location": "http://www.bbc.co.uk/, http://ocelot.com/"
},
 "HttpHandlerOptions": {
    "AllowAutoRedirect": false,
},

还可以使用BaseUrl placeholder。

"DownstreamHeaderTransform": {
    "Location": "http://localhost:6773, {BaseUrl}"
},
 "HttpHandlerOptions": {
    "AllowAutoRedirect": false,
},

如果使用了负载均衡,下游的base url可能会有多个,可能会导致上面的配置不能正常工作。这种情况下可以如下一样配置。

"DownstreamHeaderTransform": {
    "Location": "{DownstreamBaseUrl}, {BaseUrl}"
},
 "HttpHandlerOptions": {
    "AllowAutoRedirect": false,
},
posted @ 2018-09-06 15:52  irocker  阅读(805)  评论(0编辑  收藏  举报