繁体   English   中英

带有 Spring Webflux 的 HTTP 201 的绝对位置标头

[英]Absolute Location Header for HTTP 201 with Spring Webflux

我有一个反应式REST 控制器(使用 Spring WebFlux),在执行 POST 请求时,我想设置一个指向刚刚创建到强制Location标头中的资源的绝对链接。 到目前为止,我只能创建相对链接。 以任何顺序添加org.springframework.http.server.reactive.ServerHttpRequestorg.springframework.web.server.ServerWebExchange作为附加方法参数以检索主机信息等导致 HTTP 415 响应而没有到达控制器方法。

@RequestMapping("/v1/stuffs")
@RestController
public class StuffController {

    @PostMapping
    public Mono<ResponseEntity<Stuff>> createStuff(
            @Valid @NotNull @RequestBody Mono<Stuff> stuff) {
        UUID id = UUID.randomUUID();

        URI uri = UriComponentsBuilder.newInstance().pathSegment("v1", "stuffs", id.toString()).build().toUri();

        // ugly approach with help of spring-hateoas, which resulted in a relative link too
        // URI uri = WebFluxLinkBuilder.linkTo(WebFluxLinkBuilder.methodOn(StuffController.class).getStuff(id)).withSelfRel().toMono().block().toUri();

        return stuff
            .map(it -> stuffService.create(id, it))
            .map(it -> ResponseEntity.created(uri).build());
    }

    @GetMapping("/{id}")
    public Mono<ResponseEntity<Stuff>> getStuff(@NotNull @PathVariable("id") UUID id) {
        // ...
    }

}

UriComponentsBuilder componentsBuilder添加到控制器的方法签名应该使它工作:

@PostMapping
public Mono<ResponseEntity<Stuff>> createStuff(
    @Valid @NotNull @RequestBody Mono<Stuff> stuff,
    UriComponentsBuilder componentsBuilder) {
    ...
    URI uri = componentsBuilder.path("/v1/stuffs/{id}").buildAndExpand(id.toString()).toUri();
    ...
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM