Spring Boot集成Spring Fox Swagger UI遇406错误求助
我之前在Spring Boot项目里集成Spring Fox Swagger UI时,也碰到过一模一样的406问题,折腾了好一会儿才找到解决办法,给你几个可行的方案试试:
1. 检查并修改消息转换器的支持媒体类型
你提到当前可接受的媒体类型只有application/json,大概率是自定义了MappingJackson2HttpMessageConverter但只配置了JSON类型,导致Swagger UI需要的text/html等类型不被支持。修改配置,添加必要的媒体类型:
@Configuration public class WebMvcConfig implements WebMvcConfigurer { @Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { MappingJackson2HttpMessageConverter jacksonConverter = new MappingJackson2HttpMessageConverter(); List<MediaType> supportedMediaTypes = new ArrayList<>(); supportedMediaTypes.add(MediaType.APPLICATION_JSON); // 添加上Swagger UI需要的媒体类型 supportedMediaTypes.add(MediaType.TEXT_HTML); supportedMediaTypes.add(MediaType.APPLICATION_XHTML_XML); jacksonConverter.setSupportedMediaTypes(supportedMediaTypes); converters.add(jacksonConverter); } }
2. 确保Spring Security放行Swagger相关资源
如果你的项目用了Spring Security,很可能是拦截了/swagger-ui.html或者相关的静态资源请求,导致无法正确加载页面。在Security配置里放行这些路径:
@Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() // 放行所有Swagger相关路径 .antMatchers("/swagger-ui.html", "/swagger-resources/**", "/v2/api-docs", "/webjars/**") .permitAll() .anyRequest().authenticated(); // 如果启用了CSRF,也需要放行Swagger的请求 http.csrf().ignoringAntMatchers("/swagger-ui.html", "/v2/api-docs"); } }
3. 确认Spring Fox与Spring Boot版本兼容
版本不兼容也会导致各种奇怪的媒体类型问题。比如Spring Boot 2.2+推荐使用Spring Fox 3.0.0及以上版本,而Spring Boot 2.x早期版本适配Spring Fox 2.9.x。如果你的版本不匹配,调整依赖:
<!-- Maven依赖示例(Spring Boot 2.2+) --> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-boot-starter</artifactId> <version>3.0.0</version> </dependency>
4. 调整内容协商配置
如果全局配置了强制只接受application/json,需要修改内容协商规则,允许Swagger相关请求使用text/html类型:
@Configuration public class WebMvcConfig implements WebMvcConfigurer { @Override public void configureContentNegotiation(ContentNegotiationConfigurer configurer) { configurer.favorPathExtension(false) .defaultContentType(MediaType.APPLICATION_JSON) // 为html类型添加支持 .mediaType("html", MediaType.TEXT_HTML) .mediaType("json", MediaType.APPLICATION_JSON); } }
先从第一个方案开始排查,因为你已经定位到媒体类型的问题,这个最可能解决你的问题。如果还是不行,再依次检查后面的配置。
内容的提问来源于stack exchange,提问作者Abderrahmane Kaci Aissa
相关产品推荐
相关产品推荐

