2
votes

i'm adding a verb to the verbs behaviors to only allow POST request for some action and if the request not a POST it should return method not allowed but this is not working it return 404 not found response not 405 Not allowed response when i'm sending a GET request instead of POST please any help

i set in my REST control the behaviors like this

public function behaviors()
{
    $behaviors = parent::behaviors();
    $behaviors['authenticator'] = [
        'class' => CompositeAuth::className(),
        'except' => ['login'],
        'authMethods' => [
            HttpBearerAuth::className(),
        ],
    ];

    $behaviors['verbs'] = [
        'class' => \yii\filters\VerbFilter::className(),
        'actions' => [
            //'index'  => ['get'],
            'login' => ['post', 'put'],
            'view' => ['get'],
            //'create' => ['get', 'post'],
            'update' => ['put'],
            //'delete' => ['post', 'delete'],
            'delete' => [''],
            'test', ['post']
        ],
    ];

    return $behaviors;
}

in the main.php

'urlManager' => [
        'enablePrettyUrl' => true,
        'enableStrictParsing' => true,
        'showScriptName' => false,
        'rules' => [
            [
                'class' => 'yii\rest\UrlRule',
                'controller' => ['v1/vendor'],
                'extraPatterns' => [
                    'POST,PUT login' => 'login',
                    'POST logout' => 'logout',
                    'POST test' => 'test'
                ],
                'tokens' => [
                    '{id}' => '<id:\\w+>'
                ]
            ],
        ],
    ]

so when i test and sent GET request to

GET localhost/mywebsite/api/web/v1/vendors/test

it return 404 not 405 status please any help

2
And what about if you try POST request? - Gytis TG
it returns 200 @EdvinTenovimas - Fadi

2 Answers

0
votes
'extraPatterns' => [
                ...
                'test' => 'test'
            ]
-1
votes

From Yii2 guideline routing: pretty url, strict parsing always throw \yii\web\NotFound\HttpException. You can update the controller's beforeAction:

public function beforeAction() {
     if (Yii::$app->getRequest()->getMethod() != 'POST') {
          throw new \yii\web\MethodNotAllowedHttpException('Only allow POST request');
     }
}