Laravel。如何根据Content-Type

问题描述 投票:1回答:1

是否可以创建一个路由,该路由基于Content-Type标头在同一URL上在不同的控制器中调用不同的动作?

我不需要此来进行测试。我需要在api.php文件中使用一些东西。

php laravel laravel-routing laravel-5.5
1个回答
0
投票

我一直在寻找这种方法,最后我根据要检查的特殊报头注册了路由。就我而言,我想使用与Content-Type相同的URL库和基于Action的库。我将所有标头放在web.php中,您可以在api.php中使用它,然后检查此内容以确认是否设置了Content-Type,如下所示:


$headers = apache_request_headers();
// check headers Content-Type is application json for any call base on json request
if(array_key_exists('Content-Type', $headers) && strtolower($headers['Content-Type']) == 'application/json'){

    // register routes that need Content-Type header
    Route::get('/dashboard', "AuthController@dashboardWithHeader");

}else{

    // register route that dont need this special header
    Route::get('/dashboard', "AuthController@dashboard");

}

通过这种方法,如果设置了Content-Type标头,则将相关的路由注册起来,反之亦然。

© www.soinside.com 2019 - 2024. All rights reserved.