ModifyRequestBody Filter

你可以使用 ModifyRequestBody 筛选器,在网关下游发送之前修改请求体。

You can use the ModifyRequestBody filter to modify the request body before it is sent downstream by the gateway.

此过滤器只能使用 Java DSL 来配置。

This filter can be configured only by using the Java DSL.

以下清单显示了如何修改请求正文过滤器:

The following listing shows how to modify a request body filter:

GatewaySampleApplication.java
import static org.springframework.cloud.gateway.server.mvc.filter.BeforeFilterFunctions.modifyRequestBody;
import static org.springframework.cloud.gateway.server.mvc.handler.GatewayRouterFunctions.route;
import static org.springframework.cloud.gateway.server.mvc.handler.HandlerFunctions.http;
import static org.springframework.cloud.gateway.server.mvc.predicate.GatewayRequestPredicates.host;
import org.springframework.http.MediaType;

@Configuration
class RouteConfiguration {

    @Bean
    public RouterFunction<ServerResponse> gatewayRouterFunctionsAddReqHeader() {
		return route("rewrite_request_obj")
				.route(host("*.rewriterequestobj.org"), http("https://example.org"))
					.before(modifyRequestBody(String.class, Hello.class, MediaType.APPLICATION_JSON_VALUE,
								(request, s) -> new Hello(s.toUpperCase())))
					.build();
    }

	record Hello(String message) { }
}

如果该请求没有正文,则会传递 RewriteFilter。应该返回 Mono.empty() 以在请求中分配一个缺失的正文。

If the request has no body, the RewriteFilter is passed null. Mono.empty() should be returned to assign a missing body in the request.