场景:手头的项目需要对外提供API服务,需要对请求数据进行签名校验。提交接口的数据会有''空字符值存在,laravel的Illuminate\Foundation\Http\Request接收到参数后,会将空字符强制转换为NULL,导致签名校验通不过。
经过一番努力,找到幕后黑手。
Illuminate/Foundation/Http组件中有定义这个中间件。
vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/ConvertEmptyStringsToNull.php
<?php
namespace Illuminate\Foundation\Http\Middleware;
class ConvertEmptyStringsToNull extends TransformsRequest
{
/**
* Transform the given value.
*
* @param string $key
* @param mixed $value
* @return mixed
*/
protected function transform($key, $value)
{
return is_string($value) && $value === '' ? null : $value;
}
}
解决方法:
既然是中间件作祟,肯定在内核中有注册。找到内核注释该中间件就好。
app/Http/Kernel.php
class Kernel extends HttpKernel
{
/**
* The application's global HTTP middleware stack.
*
* These middleware are run during every request to your application.
*
* @var array
*/
protected $middleware = [
\App\Http\Middleware\CheckForMaintenanceMode::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
//\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,//会将''转化为null
\App\Http\Middleware\TrustProxies::class,
\Illuminate\Session\Middleware\StartSession::class,
];