2011-12-21 60 views
1

我在尝试将现有的Web应用程序迁移到Lithium框架。如何覆盖POST内容类型检测?

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

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

有没有什么办法来覆盖请求的特定网址的内容类型,及时解析它?

+0

在您的控制器中,您是否可以检测到url和/或检查数据是否未提交,并对'Request'对象执行数据解码? – 2011-12-21 06:18:39

+0

@JaredFarrish如果一切都失败了,我可能会这样做,但如果可以的话,我想保留解析出控制器。 – benzado 2011-12-22 06:06:46

回答

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); 

}); 
+0

谢谢!虽然我从'php:// input'读取而不是使用数据数组(因为一个流浪'&'会将其解析为多个键和值),但这样做的确有窍门。 – benzado 2011-12-30 05:30:44

+0

这很有道理。真高兴你做到了。 – psparrow 2011-12-30 13:59:33