如何覆盖POST内容类型检测?

时间:2011-12-21 02:37:44

标签: php lithium

我正在尝试将现有的网络应用迁移到Lithium框架。

如果我将JSON编码数据发布到URL并在请求上将Content-Type标头设置为application/json,则POST'd数据会自动解析并在控制器中可用($this->request->data )。万岁。

但是,我需要支持一个没有正确设置Content-Type标头的客户端应用程序。在这种情况下,框架假定它是URL编码的表单数据,并尝试解析它。

有没有办法覆盖特定网址的请求内容类型,及时正确解析?

1 个答案:

答案 0 :(得分:1)

在bootstrap.php脚本中尝试以下操作。如果请求数据数组中只有一个项目,并且该项目可以解码,请求数据将被解码的json数据替换。

use \lithium\action\Dispatcher;

Dispatcher::applyFilter('run', function($self, $params, $chain) {

    // Only check for JSON data for a certain URL
    if($params['request']->url == 'your/url/here') {

        // If the data array only has one element and the key can be decoded as
        // JSON data, replace the request data with the decoded JSON array
        if(count($params['request']->data) == 1) {
            $keys = array_keys($params['request']->data);
            $data = $keys[0];
            if(($data = json_decode($data, true)) != null) {
                $params['request']->data = $data;
            }
        }
    }

    return $chain->next($self, $params, $chain);

});