如何返回响应实体可以是两种不同类型的单响应实体(&L;) [英] How to return a Mono<ResponseEntity> where the response entity can be of two different types

查看:22
本文介绍了如何返回响应实体可以是两种不同类型的单响应实体(&L;)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新手,我正在尝试执行以下功能:

  1. 调用userservice.LoginWebApp()

  2. 如果返回User,则返回User类型的ResponseEntity。如果为空,则返回"字符串"类型的ResponseEntity

以下代码提供了一个类型错误,因为.defaultIfEmpty()需要类型为User的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仍然能够封送UserString

@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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆