我对Symfony 3.2中的FOSRestBundle没什么问题。首先,让我展示一下配置和行动:
FOSRest conf:
fos_rest:
versioning: true
body_converter:
enabled: true
validate: true
validation_errors_argument: validationErrors
view:
mime_types:
json: ['application/vnd.service_name+json; charset=UTF-8', 'application/json; charset=UTF-8', 'application/json']
param_fetcher_listener: true
body_listener:
decoders:
json: fos_rest.decoder.json
routing_loader:
default_format: json
format_listener:
enabled: true
serializer:
serialize_null: true
路由:
api_panel_external_address_services_get:
path: /addresses/{addressId}/services
methods: GET
defaults:
_controller: AppBundle:Api/ManagementPanel/External/Address:getServices
_format: json
requirements:
addressId: \d+
动作:
/**
* @ApiDoc(
* section="Panel/External",
* resource=true,
* description="Get external services",
* requirements={
* {"name"="addressId", "dataType"="string", "description"="External address id"}
* },
* statusCodes={
* 200="Returned when success",
* 400="Returned when data has errors (did not pass validation)",
* 404="Returned when address was not found",
* }
* )
*
* @ParamConverter("externalAddress", class="Company\Model\ExternalAddress", options={"mapping"={"addressId":"id"}})
*/
public function getServicesAction(ExternalAddress $externalAddress, ConstraintViolationListInterface $validationErrors): Response
{
if ($validationErrors->count())
{
$view = $this->view($validationErrors, Response::HTTP_BAD_REQUEST);
return $this->handleView($view);
}
$externalServices = $externalAddress->getExternalServices();
$services = [];
foreach ($externalServices as $externalService)
{
$services[] = [
'id' => $externalService->getId(),
'name' => $externalService->getName(),
];
}
return $this->handleView($this->view($services, Response::HTTP_OK));
}
问题:
当我去路线/api/v1/panel/external/addresses/801/services
时,我在不同的环境中会遇到不同的错误。
邮差:
(代码:400):Could not decode JSON, syntax error - malformed JSON.
浏览器:
"code":415,"message":"Unsupported Media Type","exception":[{"message":"The format \"\" is not supported for deserialization."
但是当我删除时
, ConstraintViolationListInterface $validationErrors
和
if ($validationErrors->count())
{
$view = $this->view($validationErrors, Response::HTTP_BAD_REQUEST);
return $this->handleView($view);
}
来自Action,一切正常,我得到了JSON响应。
我做错了吗?我希望在FOSRestBundle文档中使用此$validationErrors
变量。
希望我能在这里得到一些帮助。
好的,我在代码中找到了答案。
这是http方法GET
,当我没有提供任何内容主体(json)时,会出现错误。如果您使用get
方法,则应从操作中删除$validationErrors
。
如果$method === 'GET'
,IMO应该检查FOSRestBundle。如果没有它的混乱,但仍然是完美的意义 - 当你的方法是GET
时,你不需要验证身体。
希望这可以节省一些人的搜索时间。