问题描述
我需要在中间件中拥有当前找到的控制器和操作,以便我可以进行一些身份验证.但是我发现这是不可能的,因为管道就像Middleware1-> Middleware2->执行调度-> controller @ action()-> Middleware2-> Middleware1.
I need to have the current found controller and action in a middleware, so that I can do some authentication. But I found it impossible, because the pipe is like Middleware1 -> Middleware2-> do the dispatching -> controller@action() -> Middleware2 -> Middleware1.
因此,在派遣之前,我无法获取路线信息.在$ controller-> action()之后执行此操作绝对是不正确的.
Therefore before the dispatching, I cannot get the route info. It is definitely not right to do it after the $controller->action().
我做了一些研究,发现了这一点.
I did some research and found this.
$allRoutes = $this->app->getRoutes();
$method = \Request::getMethod();
$pathInfo = \Request::getPathInfo();
$currentRoute = $allRoutes[$method.$pathInfo]['action']['uses'];
但是当像app/role/1
那样访问URI时这是行不通的,因为$allRoutes
仅具有app/role/{id}
而不是app/role/1
的索引.
But this does not work when visiting URI like app/role/1
, because $allRoutes
only have index of app/role/{id}
instead of app/role/1
.
有什么解决方法吗?
推荐答案
我找到了此问题的正确答案.我错过了一种名为Application
的routeMiddleware()
的方法.此方法注册特定于路由的中间件,该中间件在分派后调用.因此,只需使用$app->routeMiddleware()
注册您的中间件.并通过中间件中的$request->route()
获取匹配的路由信息.
I found the correct answer to this problem. I missed one method named routeMiddleware()
of Application
. This method registers the route-specific middleware which is invoked after dispatching. So Just use $app->routeMiddleware()
to register you middleware. And get the matched route info by $request->route()
in your middleware.
这篇关于我可以通过Lumen在中间件中获取当前路线信息吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!