LocaleContextHolder 在 Spring Cloud Gateway 中没有 return 确切的语言环境

LocaleContextHolder does not return exact locale in Spring Cloud Gateway

是否可以在 Spring Cloud Gateway 中获取当前语言环境?我使用 LocaleContextHolder.getLocale() 获取用户的区域设置,但它始终是 return 默认区域设置 en。 感谢您的帮助!


@Component
public class ClientVersionGatewayFilterFactory extends AbstractGatewayFilterFactory<ClientVersionGatewayFilterFactory.Config> {
    private final MessageSource messageSource;

    public ClientVersionGatewayFilterFactory(MessageSource messageSource) {
        super(Config.class);
        this.messageSource = messageSource;
    }

    @Override
    public GatewayFilter apply(Config config) {
        return new GatewayFilter() {
            @Override
            public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

                Locale locale = LocaleContextHolder.getLocale();
                String message = messageSource.getMessage("test", null, locale);

                exchange.getResponse().getHeaders().set("X-Custom-Locale", locale.getLanguage());
                exchange.getResponse().getHeaders().set("X-Custom-Test", message);

                return exchange.getResponse().setComplete();
            }
        };
    }

    public static class Config {
    }
}

我找到了解决方法。

Locale locale = LocaleContextHolder.getLocale(exchange.getLocaleContext());
String message = messageSource.getMessage("test", null, locale);

有没有人有更好的解决方案?