【发布时间】:2016-01-21 10:02:27
【问题描述】:
在我的 Api 中,我在 module.config.php 中指定了多个子路由。当使用无效路由访问 Api 时,我得到了应用程序模块的 404,但我想在 json 中返回 404。 我的想法是捕获所有无效路由并转发到控制器操作以返回有效的 json 404 响应。
我的路线配置如下:
'router' => array(
'routes' => array(
'api-host' => array(
'type' => 'Hostname',
'options' => array(
'route' => 'api.efeedback.de',
),
'may_terminate' => true,
'child_routes' => array(
'index' => array(
'type' => 'Segment',
'options' => array(
'route' => '/',
'defaults' => array(
'controller' => 'Api\Controller\Index',
'action' => 'index',
),
),
),
'imports' => array(
'type' => 'Segment',
'options' => array(
'route' => '/imports/:product_id',
'constraints' => array(
'product_id' => '[0-9]+',
),
'defaults' => array(
'controller' => 'Api\Controller\Import',
),
),
),
'reports' => array(
'type' => 'Segment',
'options' => array(
'route' => '/reports',
'defaults' => array(
'controller' => 'Api\Controller\Report',
'auth' => true,
),
),
'may_terminate' => false,
'child_routes' => array(
'ratings' => array(
'type' => 'Segment',
'options' => array(
'route' => '/ratings',
'defaults' => array(
'controller' => 'Api\Controller\Report',
'auth' => true,
),
),
'may_terminate' => false,
'child_routes' => array(
'products' => array(
'type' => 'Segment',
'options' => array(
'route' => '/products/:product_id',
'constraints' => array(
'product_id' => '[0-9]+',
),
'defaults' => array(
'controller' => 'Api\Controller\Report',
'action' => 'products'
),
),
'may_terminate' => false,
'child_routes' => array(
'advisors' => array(
'type' => 'Segment',
'options' => array(
'route' => '/advisors[/:advisor_id]',
'constraints' => array(
'advisor_id' => '[0-9]+',
),
'defaults' => array(
'controller' => 'Api\Controller\Report',
'action' => 'advisors'
),
),
),
'providers' => array(
'type' => 'Segment',
'options' => array(
'route' => '/providers[/:provider_id]',
'constraints' => array(
'provider_id' => '[0-9]+',
),
'defaults' => array(
'controller' => 'Api\Controller\Report',
'action' => 'providers'
),
),
),
),
),
),
),
),
),
),
),
),
),
通配符类型以某种方式起作用,但不适用于所有路由。但通配符已被弃用。
我怎样才能做到这一点?
【问题讨论】:
-
Application 路由不匹配时是否也会返回 json?
-
你需要尝试一下,我自己没有测试过,或者尝试拦截DISPATCH_ERROR事件并在发生时修改响应。
-
不,它也适用于我的其他模块。我现在使用了正则表达式类型,这会捕获所有不匹配的路线
标签: php routes zend-framework2