在Lumen中设置具有中间件的响应头 [英] Setting response headers with middleware in Lumen

查看:496
本文介绍了在Lumen中设置具有中间件的响应头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Lumen中的 AfterMiddleware 设置标题( X-Powered-By )微架构。不幸的是,标头没有被设置。假设中间件(如下所示)甚至没有被处理。

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 中间件setter

bootstrap/app.php middleware setter

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

我在这里遗漏了什么吗?

Am I missing something here?

推荐答案

想出来:中间件不会被处理异常(404,在我的情况下)。我的临时解决方案是直接在异常处理程序中将标题添加到响应中。

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'));
}

不幸的是,标题正在重复,即使 $ replace 默认为true。将为此开启一个新问题。

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

这篇关于在Lumen中设置具有中间件的响应头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆