3

I tried to use the context to set some value of Reactor3 in the filter of SpringCloud Gateway but in the controller,I can't get the value in the Context.

Actually, I am new to Reactor3. So please give me some tips or help, thank you very much!

//my GatewayFilter
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

    return chain.filter(exchange)
             .subscriberContext(ctx -> ctx.put("key", "hello gate"));
}

//my Controller
@ResponseBody
@RequestMapping("/test")
public Mono<String> test() {

     return Mono.subscriberContext()
            .map(ctx -> ctx.get("key"));
}

when I try to get the value of Context , it will throw an Exception "context is empty"

LI_guoyu
  • 31
  • 1
  • Seems like yor filter is not picked by spring or it is not added in the required order. You need to share your whole filter class definition. – Aniket Singla Oct 02 '21 at 03:11

1 Answers1

0

GatewayFilter is applied to gateway-proxied routes only and will not be applied to web controllers/routes automatically.

To achieve this you could register WebFilter instead

public class TestWebFilter implements WebFilter {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        return chain.filter(exchange)
                .contextWrite(ctx -> ctx.put("key", "hello gate"));
    }
}

ps

subscriberContext is deprecated. Better use contextWrite & deferContextual.

Alex
  • 4,987
  • 1
  • 8
  • 26