Setting response headers with middleware in Lumen

2019-09-18 18:24发布

问题:

I'm trying to set a header (X-Powered-By) using an AfterMiddleware in the Lumen micro-framework. Unfortunately, the header isn't being set. It is assumed that the middleware (shown below) isn't even being handled.

AfterMiddleware.php

<?php namespace App\Http\Middleware;

use Closure;

class AfterMiddleware {

    public function handle($request, Closure $next)
    {
        $response = $next($request);

        $response->header('X-Powered-By', env('APP_NAME') . '/' . env('APP_VER'));

        return $response;
    }
}

bootstrap/app.php middleware setter

$app->middleware([
    'App\Http\Middleware\AfterMiddleware'
]);

Am I missing something here?

回答1:

Figured it out: the middleware won't be handled for Exceptions (404, in my case). My temporary solution is to simply add the header to the response directly in the exception handler.

if ($e instanceof \Symfony\Component\HttpKernel\Exception\NotFoundHttpException) {
    return response(view('not-found'), 404)->header('X-Powered-By', env('APP_NAME')."/".env('APP_VER'));
}

Unfortunately, the header is being duplicated, even though $replace defaults to true. Will open a new question for that.