Spring Webflux Mono正在忽略ResponseEntity的状态并返回200 OK

时间:2020-01-19 21:31:15

标签: kotlin spring-webflux

我有一个看起来像这样的RestController

@RestController
@RequestMapping("/user")
class UserController(val userService: UserService) {

  @PostMapping("/register")
  fun register(@RequestBody body: UsernamePasswordResource): Mono<*> {
    return userService.createUser(body.username, body.password)
        .map {ResponseEntity(it, HttpStatus.CREATED)}
        .doOnError {
          if (it is DuplicateUserException){
            ResponseEntity(ErrorResource(it.message!!), HttpStatus.BAD_REQUEST)
          } else {
            ResponseEntity(ErrorResource("Internal server error"), HttpStatus.INTERNAL_SERVER_ERROR)
          }
        }
  }
}

当我使用此端点创建使用时,会以200 OK作为响应并将其作为正文:

{
  "headers": {},
  "body": {
    "username": "test7",
    "passwordEncoded": "4HxMMUI09pltEr9pyKIxsQ==",
    "description": ""
  },
  "statusCode": "CREATED",
  "statusCodeValue": 201
}

为什么我的ResponseEntity的状态被忽略并且返回200?我该如何解决?预先感谢。

1 个答案:

答案 0 :(得分:0)

当终端成功返回时,默认情况下,

Spring提供 HTTP 200(确定)响应。要返回自定义的 HTTP 状态,请使用函数上方的 @ReponseStatus 批注,然后在括号中传递状态代码。您的代码段应如下所示:

@RestController
@RequestMapping("/user")
class UserController(val userService: UserService) {

  @PostMapping("/register")
  @ResponseStatus(HttpStatus.CREATED)
  fun register(@RequestBody body: UsernamePasswordResource): Mono<*> {
    return userService.createUser(body.username, body.password)
        .map {ResponseEntity(it, HttpStatus.CREATED)}
        .doOnError {
          if (it is DuplicateUserException){
            ResponseEntity(ErrorResource(it.message!!), HttpStatus.BAD_REQUEST)
          } else {
            ResponseEntity(ErrorResource("Internal server error"), HttpStatus.INTERNAL_SERVER_ERROR)
          }
        }
  }
}