在 Laravel 5 中使用中间件非常简单,我需要任何带有 API 密钥的请求不需要有会话,我只需要这样做:
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Session\Middleware\StartSession as BaseStartSession;
class StartSession extends BaseStartSession
{
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
{
public function register()
{
$this->registerSessionManager();
$this->registerSessionDriver();
$this->app->singleton('App\Http\Middleware\StartSession');
}
}
在config/app.php
文件的providers
数组中添加:
'App\Providers\SessionServiceProvider',
你还必须在内核文件中更改它:App/Http/Kernel.php
,在$middlewareGroups
部分更改默认条目,\Illuminate\Session\Middleware\StartSession::class,
为你的新类\App\Http\Middleware\StartSession::class,
。
\Config::set('cookie.driver', 'array');
添加到代码中,以防止应用程序在响应中发送cookies。 - Marco FlorianConfig::set
didn't work for me. However,return $next($request);
worked. I also had to change the session middleware inKernel.php
- Supun Kavinda