Is there a way to add a response header to spring webflux controller endpoint? for example to the following method I have to add a custom header say 'x-my-header'
@GetMapping(value = "/search/{text}")
@ResponseStatus(value = HttpStatus.OK)
public Flux<SearchResult> search(@PathVariable(
value = "text") String text){
return searchService().find(text);
}
To set the custom header to each response, use addHeader() method of the HttpServletResponse interface. That's all about setting a header to all responses in Spring Boot.
Select the web site where you want to add the custom HTTP response header. In the web site pane, double-click HTTP Response Headers in the IIS section. In the actions pane, select Add. In the Name box, type the custom HTTP header name.
In the functional API, this is really easy; the ServerResponse
builder has builders for almost everything you need.
With the annotated controllers; you can return an ResponseEntity<Flux<T>>
and set the headers:
@GetMapping(value = "/search/{text}")
public ResponseEntity<Flux<SearchResult>> search(@PathVariable(
value = "text") String text) {
Flux<SearchResult> results = searchService().find(text);
return ResponseEntity.ok()
.header("headername", "headervalue")
.body(results);
}
Note that the updated code doesn't need the @ResponseStatus
annotation now.
UPDATE:
Apparently the solution above works; unless you have spring-cloud-starter-netflix-hystrix-dashboard
dependency. In that case you can use the following code:
@GetMapping(value = "/search/{text}")
public Mono<ResponseEntity<List<SearchResult>>> search(@PathVariable(
value = "text") String text) {
return searchService().find(text)
.collectList()
.map(list -> ResponseEntity.ok()
.header("Header-Name", "headervalue")
.body(list));
}
A couple of things to note:
Outer type should be Mono<ResponseEntity<T>>
: There is one response for request. If you declare it to be a Flux
, Spring will try to deserialize the ResponseEntity
as if it was a POJO.
You need to use an operator to transform the Flux
into a Mono
: collectList()
or single()
will do the job for you.
Checked with Spring Boot 2.0.3.RELEASE
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With