我正在使用: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');
});

我还在 Kernel.php 中的 $routeMiddleware 数组中添加了这个:

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

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

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

有人可以帮忙吗?

这是中间件:

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,
];