【问题标题】:How to configure Yii2 to accept only application/json & application/xml requests? (revoking/disallowing form-data)如何配置 Yii2 只接受 application/json & application/xml 请求? (撤销/禁止表单数据)
【发布时间】:2021-07-05 06:38:42
【问题描述】:

我已经为 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',
            ],
        ],
 ]

【问题讨论】:

    标签: php yii2 content-type


    【解决方案1】:

    用于根据请求协商响应格式的过滤器 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) . '.');
            }
        }
    }
    

    【讨论】:

    • 当请求使用不受支持的格式时,您可能应该使用yii\web\UnsupportedMediaTypeHttpException 而不是yii\web\MethodNotAllowedHttpExceptionhttps://tools.ietf.org/html/rfc7231#section-6.5.13
    • 将内容类型限制为 json 和 XML 是否有任何反弹?
    • @Theo 没有。但如果这是你的 api,请用下划线替换或使用 data[var.name] 之类的数组。
    • @SiZE 对不起,我不完全明白你想说什么。
    • @Theo 只是不要使用点)
    猜你喜欢
    • 2016-04-07
    • 2022-08-16
    • 1970-01-01
    • 2014-11-26
    • 1970-01-01
    • 1970-01-01
    • 2016-07-11
    • 2015-02-14
    • 1970-01-01
    相关资源
    最近更新 更多