spring-cloud - 如何使用全局过滤器在 spring cloud gateway 中设置响应值

标签 spring-cloud gateway

如何使用 GlobalFilter 在 springcloud gateway 中设置响应值? 我不知道在 ServerHttpResponse 中使用哪个方法。

public class AuthGlobalFilterFilter1 implements GlobalFilter, Ordered {

@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
    Object key =  exchange.getRequest().getQueryParams().get("key");
    if(key==null){
        ServerHttpResponse serverHttpResponse =  exchange.getResponse();
        serverHttpResponse.setStatusCode(HttpStatus.UNAUTHORIZED);
        //in here,I want set the value of response body.such as json string "{"status":401}"
        return exchange.getResponse().setComplete();
    }
    return chain.filter(exchange);
}

最佳答案

我已经解决了。

        ServerHttpResponse serverHttpResponse = exchange.getResponse();
    serverHttpResponse.setStatusCode(HttpStatus.OK);
    byte[] response =  "{\"status\":\"erroe\",\"message\":\"error happen\"}".getBytes(StandardCharsets.UTF_8);;
    DataBuffer buffer = exchange.getResponse().bufferFactory().wrap(response);
    return exchange.getResponse().writeWith(Flux.just(buffer));

关于spring-cloud - 如何使用全局过滤器在 spring cloud gateway 中设置响应值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51063768/

相关文章:

api - 如何实现基本的 API 网关

timeout - Azure Web App - 通过 https 连接 Azure SQL DB 时出现 504 网关错误

jhipster - 如何处理从网关到 jhipster 注册表上正确微服务的请求?

spring-cloud - 无法阻止我的服务向 Eureka 注册

java - 使用环境覆盖 Spring Cloud Config 值

spring-boot - Spring Boot 应用程序的 Consul 服务发现问题

java - RxJava 测试 : how to wait for all background tasks to complete

spring-cloud - 记录来自 hystrix 命令的错误

android - 是否可以将两个不同的默认网关添加到 android 中两个不同 NIC 的路由表中?

azure - 使用访问限制将应用程序网关 (WAFv2) 前端 IP 列入白名单会导致应用服务出现 403 错误