在 RevalidateBackHistory.php 中调用未定义的方法 Symfony\Component\HttpFoundation\BinaryFileResponse::header()

Call to undefined method Symfony\Component\HttpFoundation\BinaryFileResponse::header() in RevalidateBackHistory.php

我写了一个中间件,让用户在登录后无法再次进入登录页面。如果已经登录,它将重定向到管理面板。

代码如下:

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

        return $response->header('Cache-Control','nocache, no-store, max-age=0, must-revalidate')
             ->header('Pragma','no-cache')
             ->header('Expires','Fri, 01 Jan 1990 00:00:00 GMT');
    }

}

我在名为 NoticeController 的控制器中调用了它

 public function __construct()
        {
            $this->middleware('auth');
            $this->middleware('revalidate'); //this is the middleware
        }

我在这个controller里面也定义了一个下载文件的函数,代码是

public function downloadFile($id)
    {
        $notice = new Notice();
        $data = $notice->where('id',$id)->first();

        if (file_exists(public_path().'/uploads/files/'.$data->file))
        {
            return response()->download(public_path().'/uploads/files/'.$data->file);
        }
        else
        {
            Session()->flash('message.notice',"File not found");
            return redirect('admin/notice/info');
        }

    }

下载功能完美,我在别的控制器上也用过这个功能。但是 当我调用 downloadFile() 函数时,这个控制器内部出现了问题,它给出了以下异常。

(1/1) FatalThrowableError

调用未定义的方法Symfony\Component\HttpFoundation\BinaryFileResponse::header() 在 RevalidateBackHistory.php 中(第 20 行) 在 RevalidateBackHistory->handle(object(Request), object(Closure))in Pipeline.php(第 148 行)

如果我从构造函数中删除 revalidate 中间件,该函数可以正常工作。这个问题的解决方案是什么?

您应该使用以下代码编辑您的 handle 函数。

$response = $next($request);
$headers = [
    'Cache-Control' => 'nocache, no-store, max-age=0, must-revalidate',
    'Pragma','no-cache',
    'Expires','Fri, 01 Jan 1990 00:00:00 GMT',
];

foreach($headers as $key => $value) {
    $response->headers->set($key, $value);
}

return $response;

用于在 RevalidateBackHistory 中间件文件中设置 headers