How do I redirect users to an external URL? I implemented a controller class in Drupal 8, which redirects to an external site.  If I use \Symfony\Component\HttpFoundation\RedirectResponse, I get this error.


  Redirects to external URLs are not allowed by default, use \Drupal\Core\Routing\TrustedRedirectResponse for it.


Using \Drupal\Core\Routing\TrustedRedirectResponse, I get this error.


  The controller result claims to be providing relevant cache metadata, but leaked metadata was detected. Please ensure you are not rendering content too early.
  Returned object class: \Drupal\Core\Routing\TrustedRedirectResponse


What should I do?
Define a controller and redirect to external URL.

Use TrustedRedirectResponse class in case you know that you want to redirect to an external URL. Example below:

use Drupal\Core\Controller\ControllerBase; 
use Drupal\Core\Routing\TrustedRedirectResponse; 
class ExampleController extends ControllerBase {

  public function example() {
    return new TrustedRedirectResponse('https://google.com');  
  }
}