Laravel中间件路由组问题

时间:2015-11-21 14:16:05

标签: php laravel laravel-5.1 middleware

我正在使用:Laravel Framework版本5.1.24(LTS),我在实施中间件路由组方面遇到了很大困难。

以下是我routes.php中的内容:

Route::group(['middleware' => 'api'], function () {
    Route::get('api/users', 'UserController@getUsers');
    Route::get('api/user/{id}', 'UserController@viewUser');
    Route::post('api/user', 'UserController@addUser');
    Route::put('api/user/{id}', 'UserController@updateUser');
    Route::delete('api/user/{id}', 'UserController@deleteUser');
});

我还将其添加到$routeMiddleware中的Kernel.php数组中:

'api' => \App\Http\Middleware\ApiAuthenticate::class,

我有ApiAuthtenticate中间件设置在继续之前运行,所以我希望看到我在那里的错误处理,但我不是。我得到的是抛出的MethodNotAllowedHttpException异常。

奇怪的是,如果删除中间件路由组,并将ApiAuthenticate类添加到$middleware内的Kernel.php数组,它的行为应该完全正常(抛出我的异常) 。但是,我想在指定的路由组上使用中间件,而不是在整个全局范围内。

有人可以帮忙吗?

这是中间件:

namespace App\Http\Middleware;

use Closure;
use Session;

use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;

class ApiAuthenticate
{
    public function handle($request, Closure $next)
    {
        if ($request->header('content-type') != 'application/x-www-form-urlencoded') {
            throw new BadRequestHttpException('The request must be: Content-Type: application/x-www-form-urlencoded');
        }

        return $next($request);
    }

来自Kernel.php

protected $middleware = [
    \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
    \App\Http\Middleware\EncryptCookies::class,
    \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
    \Illuminate\Session\Middleware\StartSession::class,
    \Illuminate\View\Middleware\ShareErrorsFromSession::class,
    //\App\Http\Middleware\VerifyCsrfToken::class,
    //\App\Http\Middleware\ApiAuthenticate::class,
];

protected $routeMiddleware = [
    'auth' => \App\Http\Middleware\Authenticate::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
    'api' => \App\Http\Middleware\ApiAuthenticate::class,
];

0 个答案:

没有答案