如何返回响应实体可以是两种不同类型的单响应实体(&L;) [英] How to return a Mono<ResponseEntity> where the response entity can be of two different types
本文介绍了如何返回响应实体可以是两种不同类型的单响应实体(&L;)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是新手,我正在尝试执行以下功能:
调用userservice.LoginWebApp()
如果返回User,则返回User类型的ResponseEntity。如果为空,则返回"字符串"类型的ResponseEntity
@PostMapping("api/user/login/webApp")
public Mono<ResponseEntity> login(@RequestBody Credentials credentials, ServerWebExchange serverWebExchange) {
return userService.loginWebApp(credentials, serverWebExchange)
.map(user -> ResponseEntity.status(HttpStatus.OK).body(user))
.defaultIfEmpty(ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Invalid username or password"));
}
推荐答案
您可以使用cast
运算符向下强制转换泛型,我相信WebFlux仍然能够封送User
和String
:
@PostMapping("api/user/login/webApp")
public Mono<ResponseEntity> login(@RequestBody Credentials credentials, ServerWebExchange serverWebExchange) {
return userService.loginWebApp(credentials, serverWebExchange)
.map(user -> ResponseEntity.status(HttpStatus.OK).body(user))
.cast(ResponseEntity.class)
.defaultIfEmpty(ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Invalid username or password"));
}
这篇关于如何返回响应实体可以是两种不同类型的单响应实体(&L;)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文