如何禁用Spring Actuators的内容协商?

3

当调用actuator端点/info/health时,我希望禁用内容协商功能。

这是我的配置文件:

@Configuration
public class InterceptorAppConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(interceptor);
    }

    @Override
    public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
        configurer.defaultContentType(MediaType.APPLICATION_XML)
                .mediaType("json", MediaType.APPLICATION_JSON)
                .mediaType("xml", MediaType.APPLICATION_XML);
    }
}

当我执行 curl http://localhost:8081/health 命令时,我收到以下信息:

DefaultHandlerExceptionResolver Resolved [org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation]

然而当我在Chrome中访问同样的URL时,我收到了一个有效的响应。

在我的情况下,actuator应该被调用而没有头部信息(没有 -H 'Accept: ...')。


configurer.ignoreAcceptHeader(true) 是否符合您的需求? - Dirk Deyne
不,我仍然需要能够发送带有头信息的GET请求,例如-H 'Accept:application / json'和xml。 - Alex
2个回答

1
很不幸,我只能提供一种次优解决方案。
@Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
    configurer
            .mediaType("json", MediaType.APPLICATION_JSON)
            .mediaType("xml", MediaType.APPLICATION_XML)
            .defaultContentTypeStrategy((webRequest) -> {
                final String servletPath = ((HttpServletRequest) webRequest.getNativeRequest()).getServletPath();
                final MediaType defaultContentType = Arrays.asList("/info", "/health").contains(servletPath)
                        ? MediaType.APPLICATION_JSON : MediaType.APPLICATION_XML;
                return Collections.singletonList(defaultContentType);
            });
}

如果调用了 /info 或者 /health 端点,将返回 application/json。对于所有其他请求,使用默认的 application/xml

-2
添加defaultContentTypeStrategy并处理空或通配符接受。
@Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
    configurer.defaultContentType(MediaType.APPLICATION_XML)
    .mediaType("json", MediaType.APPLICATION_JSON)
    .mediaType("xml", MediaType.APPLICATION_XML);

    configurer.defaultContentTypeStrategy(new ContentNegotiationStrategy() {
        @Override
        public List<MediaType> resolveMediaTypes(NativeWebRequest webRequest) throws HttpMediaTypeNotAcceptableException {
            // If you want handle different cases by getting header with webRequest.getHeader("accept")
            return Arrays.asList(MediaType.APPLICATION_JSON);
        }
    });       
}

谢谢,但这只是覆盖了默认的内容类型,而默认内容类型被设置为XML“configurer.defaultContentType(MediaType.APPLICATION_XML)”。 - Alex

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接