Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding custom Response header to Spring WebFlux contoller endpoint

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);
}
like image 984
No_One Avatar asked Jul 09 '18 13:07

No_One


People also ask

How do I add a header to all responses in Spring boot?

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.

How do you add a response header?

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.


1 Answers

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:

  1. 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.

  2. 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

like image 70
MuratOzkan Avatar answered Oct 04 '22 21:10

MuratOzkan