Reading list Switch to dark mode

    Creating POST Method Controller in Magento 2.3

    Updated 26 September 2021

    In Magento 2.3, a POST method controller can be created by implementing Magento\Framework\App\Action\HttpPostActionInterface.
    But If we have lots of POST controllers in our Module, then there will need to implement this Interface in all Controllers.
    So, In this article, we will explain to you an easy and efficient way to create POST controllers in Magento 2.3.
    Firstly, create an ApiController Class, which is implementing \Magento\Framework\App\CsrfAwareActionInterface and in this class, we have implemented two methods named as createCsrfValidationException and validateForCsrf.

    namespace Vendor\Module\Controller;
    
    use Magento\Framework\Controller\ResultFactory;
    use Magento\Framework\App\RequestInterface;
    use Magento\Framework\App\Request\InvalidRequestException;
    
    abstract class ApiController extends \Magento\Framework\App\Action\Action implements \Magento\Framework\App\CsrfAwareActionInterface
    {
         protected $_helper;
     
         public function __construct(\Magento\Framework\App\Action\Context $context ) {
             parent::__construct($context); 
         } 
        /** * @inheritDoc */ 
        public function createCsrfValidationException( RequestInterface $request ): ?       InvalidRequestException { 
             return null; 
        } 
         /** * @inheritDoc */ 
        public function validateForCsrf(RequestInterface $request): ?bool {     
            return true; 
       }
    }

    Then, we extend the ApiController class in our POST/GET method controllers.

    namespace Vendor\Module\Controller\Contact;
    class Post extends \Vendor\Module\Controller\ApiController {
      public function execute() {    
         // write your code here 
      }
    }

    I hope It will help you. Thanks 🙂 🙂

    Previous Blog: Profiler in Magento 2

    Next Blog: Display collection records in a specific order except for DESC or ASC sort order

    Searching for an experienced
    Magento 2 Company ?
    Find out More
    . . .

    Leave a Comment

    Your email address will not be published. Required fields are marked*


    2 comments

  • keon
    • khushboo sahu (Moderator)
  • Back to Top

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home