仅允许在laravel中的POST请求上使用内容类型json

仅允许在laravel中的POST请求上使用内容类型json,json,laravel,api,Json,Laravel,Api,我正在构建一个LaravelAPI,在发布数据时,我需要能够只接受“application/json”类型的请求。任何其他内容类型都应返回406“不可接受”响应 我知道我可以加入一些中间件来检查这一点,但是我想知道是否有更好的方法来实现这一点 感谢使用此中间件: class WeWantJsonMiddleware { /** * We only accept json * * @param \Illuminate\Http\Request $reque

我正在构建一个LaravelAPI,在发布数据时,我需要能够只接受“application/json”类型的请求。任何其他内容类型都应返回406“不可接受”响应

我知道我可以加入一些中间件来检查这一点,但是我想知道是否有更好的方法来实现这一点

感谢使用此中间件:

class WeWantJsonMiddleware
{
    /**
     * We only accept json
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (!$request->isMethod('post')) return $next($request);


        $acceptHeader = $request->header('Accept');
        if ($acceptHeader != 'application/json') {
            return response()->json([], 406);
        }

        return $next($request);
    }
}
(修改)

并将其添加到
App\Http\Kernel
$middleware
中,以检查每个post请求。如果您只想检查API POST请求,只需将其放入
$middlewareGroups['API']

这是我的两分钱:

class JsonMiddleware
{
    /**
     * Accept JSON only
     *
     * @param Request $request
     * @param Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $header = $request->header('Accept');
        if ($header != 'application/json') {
            return response(['message' => 'Only JSON requests are allowed'], 406);
        }

        if (!$request->isMethod('post')) return $next($request);

        $header = $request->header('Content-type');
        if (!Str::contains($header, 'application/json')) {
            return response(['message' => 'Only JSON requests are allowed'], 406);
        }

        return $next($request);
    }
}

简单使用如下中间件:

仅类AcceptJsonMiddleware
{
/**
*我们只接受json
*
*@param\light\Http\Request$Request
*@param\Closure$next
*@返回混合
*/
公共函数句柄($request,Closure$next)
{
//验证POST请求是否为JSON
如果($request->isMethod('post')&&!$request->expectsJson()){
返回响应(['message'=>'只允许JSON请求'],406);
}
返回$next($request);
}
}

中间件似乎是过滤请求类型的最佳选择。有没有一种方法我只能在post请求上强制执行此操作,而无需专门将中间件添加到每个post路由?当然,我会发布一个答案谢谢您的回答,如果所有post路由都在routes文件中,那么这很好,但我有一个结构,该结构已经使用路由的多个前缀进行分组,因此如果我添加此中间件,我必须专门将此中间件添加到每个post路由。正如我所知,所有投递路线都需要此检查。有什么方法可以全局应用此检查吗?@SamBremner抱歉,我误读了你的评论,你想将其应用于所有
post
路线吗?那也有可能让我快速改变我的想法answer@SamBremner我现在已经把我的答案完善了,这正是我所需要的。谢谢:)@SamBremner谢谢你的检查:)我现在得了10000分