我想在Yii2 REST api中的actionViewSlug($slug)
中声明一个方法ScholarshipController
,我的方法显示Not Found,而不是REST方式,即JSON。
以下是ScholarshipController
[
'class' => 'yii\rest\UrlRule',
'controller' => ['scholarship'],
'extraPatterns' => [
'POST filters' => 'filters',
'GET {slug}' => 'view-slug',
],
'tokens' => [
'{slug}' => '<slug>'
],
],
这是behaviors()
ScholarshipController
函数
public function behaviors()
{
return [
[
'class' => 'yii\filters\ContentNegotiator',
'only' => ['view', 'index', 'filters', 'view-slug'], // in a controller
// if in a module, use the following IDs for user actions
// 'only' => ['user/view', 'user/index']
'formats' => [
'application/json' => Response::FORMAT_JSON,
],
],
'corsFilter' => [
'class' => \yii\filters\Cors::className(),
'cors' => [
'Origin' => ['*'],
'Access-Control-Request-Method' => ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'],
'Access-Control-Request-Headers' => ['*'],
'Access-Control-Allow-Credentials' => null,
'Access-Control-Max-Age' => 86400,
'Access-Control-Expose-Headers' => [],
],
],
];
}
答案 0 :(得分:-1)
尝试此网址规则可能会对您有所帮助。 但是如果你继续使用这个规则,我想要清除你,如果你正在使用模块for rest API,你必须在规则中使用前缀或直接
来定义模块ID。[
'class' => 'yii\rest\UrlRule',
'controller' => '<moduleID>/scholarships',
'tokens' => [
'{slug}' => '<slug>',
],
'extraPatterns' => [
'GET,HEAD {slug}' => 'view-slug',
]
],
你在哪里actionViewSlug($ slug); 如果您共享控制器代码也很好。使用不同动作的slug很简单。还有一件事我想知道为什么要定义viewSlug动作?为什么你没有使用现有的视图动作与slug? 感谢