如何配置 Yii2 只接受 application/json & application/xml 请求? (revoking/disallowing 表单数据)

How to configure Yii2 to accept only application/json & application/xml requests? (revoking/disallowing form-data)

我已经为 json 和 XML 请求设置了我的应用程序的内容协商器,但这并不能阻止发送表单数据,在某些情况下会破坏密钥,因为点和空格正在转换为下划线见:Why . (dot) and space are changed to _ (underscores) in PHP $_GET array?

设置内容协商器和解析器都不能阻止这种情况,文档也没有提到任何“可撤销”的内容类型。

'bootstrap' => [
    'log', [
        'class' => 'yii\filters\ContentNegotiator',
        'formats' => [
            'application/json' => Response::FORMAT_JSON,
            'application/xml' => Response::FORMAT_XML,
        ],
    ],
]
'components' => [
    'request' => [
            'parsers' => [
                'application/json' => 'yii\web\JsonParser',
            ],
        ],
 ]

用于根据请求协商响应格式的过滤器 ConentNegotiator。

您需要创建自己的请求过滤器。例如,您可以使用 VerbFilter.

最常见的示例可能是

class ContentTypeFilter extends Behavior
{
    public $contentTypes = [];

    // other code here ...

    public function beforeAction($event)
    {
        if (!$this->contentTypes) {
            return $event->isValid;
        }

        $contentType = Yii::$app->getRequest()->getContentType();
        if (!in_array($contentType, $this->contentTypes)) {
             $event->isValid = false;
             throw new \yii\web\UnsupportedMediaTypeHttpException('Method Not Allowed. This URL can only handle the following request content types: ' . implode(', ', $this->contentTypes) . '.');
        }
    }
}