我正在尝试将现有的web应用程序迁移到Lithium框架。
如果我将json编码的数据POST到一个URL,并在请求时将Content-Type头设置为application/json
,则POST后的数据将自动解析并在控制器中可用(作为$this->request->data
)。万岁。
然而,我需要支持一个客户端应用程序,它没有正确设置Content-Type头。在这种情况下,框架假定它是url编码的表单数据,并尝试解析它。
是否有任何方法可以覆盖请求的特定URL的Content-Type,以便及时正确解析?
在您的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);
});