場景:手頭的項目須要對外提供API服務,須要對請求數據進行簽名校驗。提交接口的數據會有''空字符值存在,laravel的Illuminate\Foundation\Http\Request接收到參數後,會將空字符強制轉換爲NULL,致使簽名校驗通不過。php
通過一番努力,找到幕後黑手。
Illuminate/Foundation/Http組件中有定義這個中間件。
vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/ConvertEmptyStringsToNull.phplaravel
<?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.phpapp
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, ];