1

我正在尝试将现有的 Web 应用程序迁移到Lithium框架。

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

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

是否有任何方法可以覆盖特定 URL 的请求的 Content-Type,以便及时正确解析它?

4

1 回答 1

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

});
于 2011-12-22T18:40:02.223 回答