diff --git a/Request.php b/Request.php index a5e50eb79..33f4efb5e 100644 --- a/Request.php +++ b/Request.php @@ -1590,7 +1590,9 @@ public function isNoCache() * Gets the preferred format for the response by inspecting, in the following order: * * the request format set using setRequestFormat * * the values of the Accept HTTP header - * * the content type of the body of the request. + * + * Note that if you use this method, you should send the "Vary: Accept" header + * in the response to prevent any issues with intermediary HTTP caches. */ public function getPreferredFormat(?string $default = 'html'): ?string { diff --git a/Response.php b/Response.php index 714109d53..b9177934a 100644 --- a/Response.php +++ b/Response.php @@ -275,7 +275,7 @@ public function prepare(Request $request) } else { // Content-type based on the Request if (!$headers->has('Content-Type')) { - $format = $request->getPreferredFormat(null); + $format = $request->getRequestFormat(null); if (null !== $format && $mimeType = $request->getMimeType($format)) { $headers->set('Content-Type', $mimeType); } diff --git a/Tests/ResponseTest.php b/Tests/ResponseTest.php index d5da59ad7..c766f88a2 100644 --- a/Tests/ResponseTest.php +++ b/Tests/ResponseTest.php @@ -497,12 +497,25 @@ public function testPrepareDoesNothingIfRequestFormatIsNotDefined() $this->assertEquals('text/html; charset=UTF-8', $response->headers->get('content-type')); } + /** + * Same URL cannot produce different Content-Type based on the value of the Accept header, + * unless explicitly stated in the response object. + */ + public function testPrepareDoesNotSetContentTypeBasedOnRequestAcceptHeader() + { + $response = new Response('foo'); + $request = Request::create('/'); + $request->headers->set('Accept', 'application/json'); + $response->prepare($request); + + $this->assertSame('text/html; charset=UTF-8', $response->headers->get('content-type')); + } + public function testPrepareSetContentType() { $response = new Response('foo'); $request = Request::create('/'); $request->setRequestFormat('json'); - $request->headers->remove('accept'); $response->prepare($request);