0

I've set up my application's content negotiator for json and XML requests but this does not prevent sending in form-data which in some cases breaks the keys because dots and spaces are being converted to underscores see: Why . (dot) and space are changed to _ (underscores) in PHP $_GET array?

Both setting the content negotiator and the parser does not prevent this and the docs did not mention any "revokable" content types.

'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',
            ],
        ],
 ]
Theo
  • 2,262
  • 3
  • 23
  • 49

1 Answers1

1

The filter ConentNegotiator used to negotiate response format based on request.

You need to create your own request filter. As an example you can use VerbFilter.

The most common sample could be

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) . '.');
        }
    }
}
SiZE
  • 2,217
  • 1
  • 13
  • 24
  • 2
    You should probably use `yii\web\UnsupportedMediaTypeHttpException` instead of `yii\web\MethodNotAllowedHttpException` when the request uses unsupported format. [https://tools.ietf.org/html/rfc7231#section-6.5.13](https://tools.ietf.org/html/rfc7231#section-6.5.13) – Michal Hynčica Apr 09 '21 at 16:34
  • is there any backlash in restricting the content types to json and XML? – Theo Apr 09 '21 at 23:47
  • @Theo no. But if this is ur api replace with underscore or use array like `data[var.name]`. – SiZE Apr 11 '21 at 02:05
  • @SiZE sorry I don't fully understand what you are trying to say. – Theo Apr 11 '21 at 23:59
  • @Theo just don't use dots) – SiZE Apr 12 '21 at 06:32