AddRequestHeadersIfNotPresent Filter

AddRequestHeadersIfNotPresent 过滤器使用冒号分隔的一组 namevalue 对。以下示例配置了一个 AddRequestHeadersIfNotPresent 过滤器:

The AddRequestHeadersIfNotPresent filter takes a collection of name and value pairs separated by colon. The following example configures an AddRequestHeadersIfNotPresent filter:

application.yml
spring:
  cloud:
    gateway:
      mvc:
        routes:
        - id: add_request_headers_route
          uri: https://example.org
          filters:
          - AddRequestHeadersIfNotPresent=X-Request-Color-1:blue,X-Request-Color-2:green
GatewaySampleApplication.java
import static org.springframework.cloud.gateway.server.mvc.filter.BeforeFilterFunctions.addRequestHeadersIfNotPresent;
import static org.springframework.cloud.gateway.server.mvc.handler.GatewayRouterFunctions.route;
import static org.springframework.cloud.gateway.server.mvc.handler.HandlerFunctions.http;

@Configuration
class RouteConfiguration {

    @Bean
    public RouterFunction<ServerResponse> gatewayRouterFunctionsAddReqHeader() {
        return route(GET("/red"), http("https://example.org"))
                .before(addRequestHeadersIfNotPresent("X-Request-Color-1:blue","X-Request-Color-2:green"));
    }
}

这个清单为所有匹配请求将 2 个标头 X-Request-Color-1:blueX-Request-Color-2:green 添加到下游请求标头中。这类似于 AddRequestHeader 的工作方式,但与 AddRequestHeader 不同,它仅在标头不存在时才会执行此操作。否则,将发送客户端请求中的原始值。

This listing adds 2 headers X-Request-Color-1:blue and X-Request-Color-2:green to the downstream request’s headers for all matching requests. This is similar to how AddRequestHeader works, but unlike AddRequestHeader it will do it only if the header is not already there. Otherwise, the original value in the client request is sent.

此外,要设置多值标头,需多次使用标头名称,例如 addRequestHeadersIfNotPresent("X-Request-Color-1:blue","X-Request-Color-1:green")

Additionally, to set a multi-valued header, use the header name multiple times like addRequestHeadersIfNotPresent("X-Request-Color-1:blue","X-Request-Color-1:green").

AddRequestHeadersIfNotPresent 还支持用于匹配路径或主机的 URI 变量。URI 变量可用于值,并会在运行时进行展开。以下示例配置了一个使用变量的 AddRequestHeadersIfNotPresent 过滤器:

AddRequestHeadersIfNotPresent also supports URI variables used to match a path or host. URI variables may be used in the value and are expanded at runtime. The following example configures an AddRequestHeadersIfNotPresent filter that uses a variable:

GatewaySampleApplication.java
@Configuration
class RouteConfiguration {

    @Bean
    public RouterFunction<ServerResponse> gatewayRouterFunctionsAddReqHeader() {
        return route(GET("/red/{segment}"), http("https://example.org"))
                .before(addRequestHeadersIfNotPresent("X-Request-red", "blue-{segment}"));
    }
}
application.yml
spring:
  cloud:
    gateway:
      routes:
      - id: add_request_header_route
        uri: https://example.org
        predicates:
        - Path=/red/{segment}
        filters:
        - AddRequestHeadersIfNotPresent=X-Request-Red:Blue-{segment}