Search code examples
javahttp-headersquarkusresteasycontext-injection

How do I get the requests HttpHeaders in a CDI bean in Quarkus?


I would like to get the AcceptableLanguage header of the originating request to select the correct translation language.

I thought that this would work:

import javax.ws.rs.core.HttpHeaders;

@ApplicationScoped
public class TranslationService{

   @Context HttpHeaders httpHeaders;
....
}

As it seems, I always result in a null value. When I try the @Context field directly in a RestEasy controller, the field is assigned with the current HttpHeaders object.

I already have tried to save the http headers inside a ContrainerRequestFilter to a @RequestScoped bean, althought the value seems to get lost again until the use in my TranslationService.

How can I, in quarkus, get or provide the requests http headers, so any bean can access them?


Solution

  • It actually did work with a ContainerRequestFilter

    I added the following filter

    @Provider
    @PreMatching
    public class UserInfoProvider implements ContainerRequestFilter {
    
        private final UserInfo userinfo;
    
        @Inject
        public UserInfoProvider(UserInfo userinfo) {
            this.userinfo = userinfo;
        }
    
        @Override
        public void filter(ContainerRequestContext requestContext) {
            List<Locale> acceptableLanguages = requestContext.getAcceptableLanguages();
            userinfo.setAcceptableLanguages(acceptableLanguages);
        }
    }
    

    of which the bean UserInfo is @RequestScoped