0

I am trying to redirect in my controller_action_predispatch observer. However, I got http 500 error, unable to handle the request

Note: I got the error 500 once i include \Magento\Framework\App\Response\Http $http (even if i don't do the redirect logic inside)

What could be the problem?

<?php
namespace Vendor\Name\Observer;

use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;

class RedirectObserver implements ObserverInterface
{
    protected $accountRedirect;
    protected $session;
    protected $url;
    protected $http;

    public function __construct(
        \Magento\Customer\Model\Account\Redirect $accountRedirect,
        \Magento\Customer\Model\Session $session,
        \Magento\Framework\UrlInterface $url,
        \Magento\Framework\App\Response\Http $http
    ) {
        $this->accountRedirect = $accountRedirect;
        $this->session = $session;
        $this->url = $url;
        $this->http = $http;
    }

    public function execute(Observer $observer)
    {
        if (!$this->session->isLoggedIn()) {
            // redirect to login page
            $this->http->setRedirect($this->url->getUrl('customer/account/login'), 301);
        }
    }
}
1

1 Answer 1

1

Should try with

 <preference for="Magento\Framework\App\Response\RedirectInterface" type="Magento\Store\App\Response\Redirect" />

Magento\Framework\App\Response\RedirectInterface or Magento\Store\App\Response\Redirect. A good example Magento 2 - Redirect user to a specific page if not logged in

5
  • I tried the sample given with \Magento\Framework\App\Response\RedirectInterface on controller action predispatch observe but not working. still http error 500. Should i add the preference for it to work? Where should i add the preference in. Commented Feb 1, 2018 at 4:07
  • I'm pretty sure the link I gave you it will work. Please, check other parts. Commented Feb 1, 2018 at 4:09
  • No, I just show you the preference. Don't to do anything with it. Commented Feb 1, 2018 at 4:10
  • It works after i remove all the var/pub folder and static deploy again. Do i have to do it all the time? I am in developer mode. Commented Feb 1, 2018 at 6:54
  • Don't need to do static deploy every time in developer mode. Just delete pub/static, not delete .htaccess. And then refresh the page again. The static content will be generated on fly and symlink. Commented Feb 2, 2018 at 1:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.