有没有办法重定向到Yii 2中的行为方法登录以外的页面?
我的行为方法内容:
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['post'],
],
],
'access' => [
'class' => AccessControl::className(),
'only' => [ 'create','update' ],
'rules' => [
[
'allow' => true,
'actions' => [ 'create'],
'roles' => ['@'],
],
[
'allow' => true,
'actions' => ['logout'],
'roles' => ['?'],
],
],
],
];
}
Run Code Online (Sandbox Code Playgroud)
但它重定向到登录.我需要指定另一个重定向页面或调用:
throw new \yii\web\HttpException(403, 'The requested Item could not be found.');
Run Code Online (Sandbox Code Playgroud)
aro*_*hev 20
你需要改变类的loginUrl属性yii\web\User.
如果要全局更改,请编辑配置:
'components' => [
'user' => [
'loginUrl' => ['site/sign-in'],
],
],
Run Code Online (Sandbox Code Playgroud)
如果您需要在特定控制器或操作中更改它,您也可以这样设置:
Yii::$app->user->loginUrl = ['site/sign-in'];
Run Code Online (Sandbox Code Playgroud)
您需要beforeAction()在控制器中覆盖需要执行此操作的方法.在此事件中执行所有访问chesks.
/**
* @inheritdoc
*/
public function beforeAction($action)
{
if (parent::beforeAction($action)) {
// If you want to change it only in one or few actions, add additional check
Yii::$app->user->loginUrl = ['site/sign-in'];
return true;
} else {
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
您可以从denyCallback()中受益,正如Yii2官方文档所定义的那样:
如果应拒绝当前用户访问将调用的回调.如果未设置,将调用denyAccess().
回调的签名应如下:
function ($rule, $action)
Run Code Online (Sandbox Code Playgroud)
$rule拒绝用户的规则在哪里,并且$action是当前操作对象.$rule如果访问被拒绝,则可以为null,因为没有匹配的规则.
举个例子:
'denyCallback' => function($rule, $action) {
if ($something) {
//set flash for example
Yii::$app->session->setFlash('key', 'Value');
//Redirect
return $action->controller->redirect('action');
}
//as a default behavior, it throws an exception
throw new ForbiddenHttpException("Forbidden access");
},
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
20134 次 |
| 最近记录: |