【问题标题】:Spring Boot Rest - How to accept multiple headersSpring Boot Rest - 如何接受多个标头
【发布时间】:2020-01-13 09:23:25
【问题描述】:

我正在使用 Spring Boot V2.2.2.RELEASE 并使用自定义标头进行 API 版本控制。我开发了这样的小端点:

@GetMapping(value = "/student/header", headers = {"X-API-VERSION=2", "X-API-VERSION=1"})
public StudentV1 headerV2() {
    return new StudentV1("Bob Charlie");
} 

当我点击curl -X GET http://localhost:8080/student/header -H 'x-api-version: 1' 时,我得到了错误。

{
    "timestamp": "2020-01-13T09:20:20.087+0000",
    "status": 404,
    "error": "Not Found",
    "message": "No message available",
    "path": "/student/header"
}

如果我使用headers = {"X-API-VERSION=2"},那么它可以工作,但如果我使用headers = {"X-API-VERSION=2", "X-API-VERSION=1"},那么事情就停止了。

@GetMapping(value = "/student/header", headers = {"X-API-VERSION=2"})
public StudentV1 headerV2() {
  return new StudentV1("Bob Charlie");
}

【问题讨论】:

    标签: spring swagger spring-rest


    【解决方案1】:

    使用headers = {"X-API-VERSION=2", "X-API-VERSION=1"} 两个标头都必须存在。

    尝试每个标头使用一个映射,然后转发到您的服务实现。

    @GetMapping(value = "/student/header", headers = {"X-API-VERSION=1"})
    public StudentV1 headerV1() {
        return serviceImpl.headerV1();
    }
    
    @GetMapping(value = "/student/header", headers = {"X-API-VERSION=2"})
    public StudentV1 headerV2() {
        return serviceImpl.headerV2();
    }
    

    【讨论】:

    • 您需要实现自定义处理程序...codeboje.de/spring-mvc-argument-mapping-basics
    • 两个标题都存在时应该调用哪个版本?或者只是添加第三个映射,headers = {"X-API-VERSION=2", "X-API-VERSION=1"}
    • 如果我通过了版本 1,那么应该调用与版本 1 相关的逻辑,然后我通过版本 1,然后是与版本 2 相关的逻辑。我怀疑我需要在控制器上提供 if else 对我来说看起来很糟糕
    • @Alexander - 尝试对每个标头使用一个映射,然后转发到公共服务实现。 - 你能分享一些代码吗?
    猜你喜欢
    • 1970-01-01
    • 2019-05-10
    • 2017-06-21
    • 1970-01-01
    • 2022-06-29
    • 1970-01-01
    • 2022-08-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多