ModifyRequestBody 过滤器
您可以使用 ModifyRequestBody 过滤器在网关将请求主体发送到下游之前对其进行修改。
| 此过滤器只能通过 Java DSL 进行配置。 |
以下列表展示了如何修改请求主体过滤器
GatewaySampleApplication.java
import static org.springframework.cloud.gateway.server.mvc.filter.BeforeFilterFunctions.modifyRequestBody;
import static org.springframework.cloud.gateway.server.mvc.filter.BeforeFilterFunctions.uri;
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> gatewayRouterFunctionsModifyRequestBody() {
return route("modify_request_body")
.route(host("*.modifyrequestbody.org"), http())
.before(uri("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 会传递 null。应该返回 Mono.empty() 以指定请求中缺少主体。 |