ed.sukharev/request-headers-param-converter

此参数转换器为 Sensio Framework Extra Bundle 添加了方便的 HTTP 头部处理功能

v1.1.0 2021-01-26 11:00 UTC

This package is auto-updated.

Last update: 2024-09-26 20:13:23 UTC


README

本包包含一个简单且方便的 ParamConverter,用于将 HTTP 头部注入到控制器动作中。

有关 SensioFrameworkExtraBundle 的信息,请访问其官方主页

用法

RequestHeader 定义为一个服务(在 config.yml 中)

services:
    EdSukharev\App\ParamConverter\RequestHeaders:
        tags:
            - { name: 'request.param_converter', converter: 'request_header_converter', priority: '-60' }

然后在您的控制器中

namespace App\Controller\Api;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Routing\Annotation\Route;

class ApiController
{
    /**
     * @Route("/", methods={"GET"})
     * @ParamConverter("XAuthenticatedUserId", class="int", isOptional=true, converter="request_header_converter")
     * @ParamConverter("ContentType", class="string", isOptional=false, converter="request_header_converter")
     * @ParamConverter("XRequireAuth", class="string", isOptional=false, converter="request_header_converter")
     */
    public function getUserInfo($xAuthenticatedUserId, $contentType, $xRequireAuth) {
        return new JsonResponse([
            'XAuthenticatedUserId' => $xAuthenticatedUserId,
            'ContentType' => $contentType,
            'XRequireAuth' => $xRequireAuth,
        ]);
    }
}

然后,提供以下请求

curl localhost -H 'x-require-auth: false' -H 'content-type: application/json'

响应将是

{
  "XAuthenticatedUserId": null,
  "ContentType": "application/json",
  "XRequireAuth": false
}

注解参数

ParamConverter 注解接收以下参数作为参数:- name — 要查找的头部名称,也用于生成控制器动作参数名称 - class — 定义参数类型。默认情况下,所有接收到的头部作为字符串处理。 - isOptional — 当头部缺失时,如果此设置为 false,则将抛出 \EdSukharev\App\ParamConverter\MissingHeaderException,否则将参数值设置为 null。 - converter — 必须为 request_header_converter,以便此请求参数由该库处理。