在 Laravel 5 中使用中间件真的很容易,我需要任何带有 API 密钥的请求而不需要会话,我只是这样做了:
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Session\Middleware\StartSession as BaseStartSession;
class StartSession extends BaseStartSession
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if(\Request::has('api_key'))
{
\Config::set('session.driver', 'array');
}
return parent::handle($request, $next);
}
}
此外,您还需要扩展 SessionServiceProvider,如下所示:
<?php namespace App\Providers;
use Illuminate\Session\SessionServiceProvider as BaseSessionServiceProvider;
class SessionServiceProvider extends BaseSessionServiceProvider
{
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->registerSessionManager();
$this->registerSessionDriver();
$this->app->singleton('App\Http\Middleware\StartSession');
}
}
并放置在你的config/app.php
under providers
:
'App\Providers\SessionServiceProvider',
您还必须在内核文件中更改它:App/Http/Kernel.php
, 在里面$middlewareGroups
部分更改默认条目,\Illuminate\Session\Middleware\StartSession::class,
到你的新班级\App\Http\Middleware\StartSession::class,
.