Php 如何将Yii2配置为仅接受application/json&;应用程序/xml请求?(撤销/禁止表单数据)
我已经为json和XML请求设置了应用程序的内容协商器,但这并不能阻止以表单形式发送数据,在某些情况下,由于点和空格被转换为下划线,这些数据会破坏键。请参见: 设置内容协商器和解析器都不会阻止这一点,文档中也没有提到任何“可撤销”的内容类型Php 如何将Yii2配置为仅接受application/json&;应用程序/xml请求?(撤销/禁止表单数据),php,yii2,content-type,Php,Yii2,Content Type,我已经为json和XML请求设置了应用程序的内容协商器,但这并不能阻止以表单形式发送数据,在某些情况下,由于点和空格被转换为下划线,这些数据会破坏键。请参见: 设置内容协商器和解析器都不会阻止这一点,文档中也没有提到任何“可撤销”的内容类型 'bootstrap' => [ 'log', [ 'class' => 'yii\filters\ContentNegotiator', 'formats' => [ 'ap
'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',
],
],
]
筛选器ConentCongregator用于根据请求协商响应格式 您需要创建自己的请求筛选器。作为一个例子,你可以使用 最常见的样本可能是
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\MethodNotAllowedHttpException
。将内容类型限制为json和XML是否有任何抵触情绪?@Theo否。但如果这是您的api,请替换为下划线或使用数组,如data[var.name]
@SiZE抱歉,我不完全理解您的意思。@Theo只是不要使用点)