我想确定请求的内容类型标头是application/json,我该如何使用Slim框架?
这是无效的:
$contentType = $app->request->getContentType();
if(strtolower($contentType)!="application/json")
throw new AppException("Request must have application/json content type");
因为内容类型可以包含字符集info等等
您可以检查标题,而不是使用快捷方式
$cType = $app->request->headers('Content-Type');
if (strpos('application/json', $cType) !== false) {
//is json
}
对于那些寻找在任何情况下都有效的解决方案的人来说,Illya Moskvin是对的,争论在geggleto答案中被转换。下面是代码示例:
$contentType = $request->getContentType();
if (strpos($contentType, 'application/json') !== false) {
//is json
}
您可以使用不区分大小写但性能较差的stripos
,或者将strtolower
应用于$contentType
我正在使用Slim 3的新版本,遇到了同样的问题。
这是一个为我工作的解决方案(从特定控制器内部)
$request_type = $request->getHeader('CONTENT_TYPE');
if($request_type[0] != 'application/json'){
// throw error
return $response->withStatus(415)
->withHeader('Content-type', 'text/html')
->write('Only json content type accepted');
}
也许这能帮到别人