Вы просматриваете документацию Apigee Edge .
Перейти к документации Apigee X. info
![]()
Что
Политика AssignMessage изменяет или создаёт новые сообщения запросов и ответов в потоке API-прокси. Политика позволяет выполнять следующие действия с этими сообщениями:
- Добавить новые параметры формы, заголовки или параметры запроса в сообщение
- Копировать существующие свойства из одного сообщения в другое
- Удалить заголовки, параметры запроса, параметры формы и/или полезную нагрузку сообщения из сообщения.
- Установить значение существующих свойств в сообщении
Политика AssignMessage обычно позволяет добавлять, изменять или удалять свойства запроса или ответа. Однако её также можно использовать для создания настраиваемого сообщения запроса или ответа и передачи его альтернативному целевому объекту, как описано в разделе Создание настраиваемых сообщений запроса .
Политика AssignMessage может создавать или изменять сообщения или переменные потока. Используйте эту политику для изменения сообщений-запросов перед их отправкой через прокси-сервер в вышестоящие системы или для изменения ответных сообщений перед их ретрансляцией в приложения-потребители API.
Элемент <AssignMessage>
Определяет политику AssignMessage.
| Значение по умолчанию | См. вкладку «Политика по умолчанию» ниже. |
| Необходимый? | Необходимый |
| Тип | Сложный объект |
| Родительский элемент | н/д |
| Дочерние элементы | <Add><AssignTo><AssignVariable><Copy><DisplayName><IgnoreUnresolvedVariables><Remove><Set> |
Элемент <AssignMessage> использует следующий синтаксис:
Синтаксис
Элемент <AssignMessage> использует следующий синтаксис:
<AssignMessage continueOnError="[false|true]" enabled="[true|false]" > na<me="policy_name" !-- All AssignMessage >chi<ld >eleme<nts are op>tional <-- Add FormParams F>ormParam name=&<quot;formp>aram_name"<formparam_v>alue/<FormPar>am < ... /FormParams > Headers < Head>er name="h<eader_na>me&qu<ot;header_v>alue/He<ader ... /Headers Q>ueryParams < QueryParam> name="que<ryparam_name>&qu<ot;q>uery<param_value/QueryParam ... /QueryParams /Add AssignTo createNew=&>quot;[true|false]" t<ransport=>&quo<t;http" > ty<pe=&>quot;[request<|resp>onse]<&qu>ot;destination_<vari>able_<name/Ass>ignTo AssignV<ariable > Namevaria<ble_name/Name Refsource_vari><able/Ref > T<empla>temessage_temp<late/T>emp<late or > Tem<plate ref='template_variable>'</Template Valuevariable_valu<e/Value />AssignVari<able Co>py sour<ce="[request|response]&quo>t; !-- Can <also be an> empty array (F<ormParams/)> --&g<t; FormParams FormPara<m name=&>quot;formp<aram_na>me"<;formparam_value/FormPara>m ... < /Fo>rmParams !-<- Can al>so be< an >empty array <(Head>ers/)< -->> Headers< H>eader< name="header_name"hea<der_value/He>ader < ... /H>eaders < Path[false|true]/Path Pay>load[false|true]</Payload > !-- Can also <be an empty >array< (QueryParam>s/) --> < QueryParam>s < QueryPa>ram name=&qu<ot;querypar>am_na<me&q>uot;querypar<am_va>lue/Q<ueryPar>am ...< /Qu>ery<Param>s < ReasonPhr>ase[false|true]/Rea<sonPhrase > St<atusCode[false|true]/Stat>usCode Verb<[false|true]/Verb Vers>ion[<false|>true]</Version /Copy DisplayNamep<olicy_displ>ay_name/Di<splayName<>/span> Igno<reUnresolvedVariables[true|fals>e] /IgnoreUnr<esolvedVar>iables Remov<e !-- C>an al<so be an empty array (FormParams</) -->>; Form<Params<>/span> F<ormParam name="formp>aram_name&qu<ot;form>param_value/For<mParam > <... > /FormParams< !--> Can <also be an empty array (Headers/<) --> > Headers < Header> name=&<quot;header_name"header_valu>e/Header .<.. /Hea>ders Payloa<d[false|true>]/P<ayload<>/span> <!--> Can <also be an> empty <array (QueryParams/) --> > QueryParams < QueryP>aram name="<;queryparam>_name<"q>uerypar<am_value/QueryParam > ... /Qu<eryPara>ms /Remove < Set > Form<Para>ms < >FormP<aram name="formparam_name"formparam_value/FormParam ... /FormParams > Headers < Hea>der n<ame="h>eader_n<ame"header_value/Header > ... /Heade<rs Path>path/Path P<ayload conte>ntTyp<e="cont>ent_type" variablePrefix=<"prefix&>quot;< v>ariableSuffix="suffix&quo<t;new_paylo>ad/Pa<yloa>d QueryParams QueryParam nam<e=&qu>ot;qu<erypara>m_name"querypar<am_va>lue</Que>ry<Param ..>. /QueryParams ReasonPhrasereason_for_error or {variable}/ReasonPhrase StatusCodeHTTP_status_code or {variable}/StatusCode Verb[GET|POST|PUT|PATCH|DELETE|{variable}]/Verb Version[1.0|1.1|{variable}]/Verb /Set /AssignMessage
Политика по умолчанию
В следующем примере показаны настройки по умолчанию при добавлении политики AssignMessage в ваш поток в пользовательском интерфейсе Edge:
<AssignMessage continueOnError="false" enabled="true" name=&quo>t;a<ssign-messa>ge-default"< DisplayNa>meA<ssign Messa>ge-<1/DisplayName Prope>rties</ Copy> sour<ce="req>uest&<quot; H>eader<s/ Q>ueryP<arams>/ < FormParams>/ < Payload/ > Verb</ > St<atusC>ode</ >Reaso<nPhrase>/ P<ath/ /Copy Re>move < Head>ers < Header> name=&<quot;h1"/ /H>eader<s QueryP>arams< Que>ryParam< name="q1">/ < /QueryPara>ms < FormPa>ram<s > Fo<rmP>aram <name=&qu>ot;f1<"/ >/Form<Params >Pay<load>/ < /R>emove< Add > He<aders/ Q>ueryP<arams/ >FormP<aram<s/ > /A<dd >Set> <Heade>rs/< > Qu<eryParams/ > Form<Para>ms/ < !>-- Ve<rbGET/>Verb <-- > <Path/ /Set >Ass<ignVariable Namename/>Name < Value/ Ref/ /Assig>nVa<riable IgnoreUnresolvedVariablestrue /IgnoreUnresolvedV>a<riables Assi>gnTo createNew="false" transport="http" type="request"/ /AssignMessage
При добавлении новой политики AssignMessage в пользовательский интерфейс Edge шаблон содержит заглушки для всех возможных операций. Обычно вы выбираете, какие операции нужно выполнить с этой политикой, и удаляете остальные дочерние элементы. Например, если вы хотите выполнить операцию копирования, используйте элемент <Copy> и удалите из политики элементы <Add> , <Remove> и другие дочерние элементы, чтобы сделать её более читабельной.
Этот элемент имеет следующие атрибуты, общие для всех политик:
| Атрибут | По умолчанию | Необходимый? | Описание |
|---|---|---|---|
name | Н/Д | Необходимый | Внутреннее имя политики. Значение атрибута При необходимости используйте элемент |
continueOnError | ЛОЖЬ | Необязательный | Установите значение «false», чтобы возвращать ошибку при сбое политики. Это ожидаемое поведение для большинства политик. Установите значение «true», чтобы выполнение потока продолжалось даже после сбоя политики. |
enabled | истинный | Необязательный | Установите значение «true», чтобы применить политику. Установите значение «false», чтобы «отключить» политику. Политика не будет применяться, даже если она остается присоединенной к потоку. |
async | ЛОЖЬ | Устаревший | Этот атрибут устарел. |
В следующей таблице представлено общее описание дочерних элементов <AssignMessage> :
| Дочерний элемент | Необходимый? | Описание |
|---|---|---|
| Общие операции | ||
<Add> | Необязательный | Добавляет информацию к объекту сообщения, указанному элементом <AssignTo> . Элемент |
<Copy> | Необязательный | Копирует информацию из сообщения, указанного атрибутом source , в объект сообщения, указанный элементом <AssignTo> . |
<Remove> | Необязательный | Удаляет указанные элементы из переменной сообщения, указанной в элементе <AssignTo> . |
<Set> | Необязательный | Заменяет значения существующих свойств в запросе или ответе, указанном элементом <AssignTo> . |
| Другие дочерние элементы | ||
<AssignTo> | Необязательный | Указывает, к какому сообщению применяется политика AssignMessage. Это может быть стандартный запрос или ответ, либо новое пользовательское сообщение. |
<AssignVariable> | Необязательный | Присваивает значение переменной потока. Если переменная не существует, метод <AssignVariable> создаёт её. |
<IgnoreUnresolvedVariables> | Необязательный | Определяет, останавливается ли обработка при обнаружении неразрешенной переменной. |
Каждый из этих дочерних элементов описан в следующих разделах.
Примеры
В следующих примерах показаны некоторые способы использования политики AssignMessage:
1: Добавить заголовок
В следующем примере к запросу добавляется заголовок с элементом <Add> :
<AssignMessage name="AM-add-heade>rs-<1&q>uot;
< Add
> Head<ers
Header name=&q>uot;partner-id"{verifyapikey.VAK-1.devel<oper.ap>p.par<tner-id}>/He<ader>
< /Heade>rs
/A<dd
Assi>g<nTorequest/Ass>ignTo
/AssignMessage2: Удалить полезную нагрузку
В следующем примере полезная нагрузка удаляется из ответа с помощью элемента <Remove> :
<AssignMessage name="AM-remo>ve-<1" D>isplayNa<meremove-1/D>isp<layNam>e R<emove > P<ayloadtr>ue/<Payload> </Remove > Assign<Torespons>e</AssignTo /Ass>ignMessage
3: Изменить ответ
В следующем примере существующий объект ответа изменяется путем добавления к нему заголовка:
<AssignMessage name="AM-modify-resp>ons<e&q>uot;
< Set
> Head<ers
Header name=&>quot;Cache-Hit"{lookupcache.Loo<kupCach>e-1.c<achehit}>/He<ader>
< /Headers
/Set
Ignor>eUnresol<vedVariablesfalse
/Ignor>eUn<resolved>Variable<s
Assig>n<Toresponse/Ass>ignTo
/AssignMessageЭтот пример не создаёт новое сообщение. Вместо этого он изменяет существующее ответное сообщение, добавляя HTTP-заголовок.
Поскольку в этом примере response указан как имя переменной в элементе <AssignTo> , эта политика изменяет объект response, который был изначально установлен с данными, возвращаемыми целевым сервером.
HTTP-заголовок, добавляемый к ответному сообщению этой политикой, извлекается из переменной, заполняемой политикой LookupCache . Поэтому ответное сообщение, изменённое этой политикой Assign Message, содержит HTTP-заголовок, указывающий, были ли результаты извлечены из кэша. Настройка заголовков в ответе может быть полезна для отладки и устранения неполадок.
4. Установите динамический контент
Вы можете использовать функцию Assign Message для встраивания динамического контента в полезную нагрузку сообщений-ответов и запросов.
Чтобы встроить переменные потока Edge в полезную нагрузку XML, заключите указанную переменную в фигурные скобки, например: {prefix.name} .
В следующем примере значение переменной потока HTTP-заголовка user-agent встраивается в элемент XML с именем User-agent :
<AssignMessage name="AM-set-dynamic-con>ten<t"<>/span> Assign<Torespons>e/A<ssi>gnTo < Set Payload contentType=>"t<ext/xml&qu>ot; User-agent{reques<t.header.us>er-ag<ent}/Use>r-a<gent> < /Payload /Set Ignor>eUnresol<vedVariablesfalse /Ignor>e<UnresolvedVari>ables /AssignMessage
Для полезных данных JSON вы можете вставлять переменные, используя атрибуты variablePrefix и variableSuffix с символами-разделителями, как показано в следующем примере:
<AssignMessage name="set-pay>loa<d" Payload contentType="application/json" variablePrefix=&q>uot;@" variableSuffix="#" { "user<-agent&q>u<ot;: "@re>quest.header.user-agent#" } /Payload /AssignMessage
Полный список переменных потока см. в Справочнике переменных потока .
Начиная с версии Cloud 16.08.17 для вставки переменных также можно использовать фигурные скобки.
5: Удалить параметр запроса
В следующем примере параметр запроса apikey удаляется из запроса:
<AssignMessage name="AM-remove-query-p>ara<m">;
R<emove
Q>ueryPar<ams
QueryParam name>=&quo<t;apikey&quo>t;/<
/Q>uer<yParams
> /Remo<ve
Assi>g<nTorequest/Ass>ignTo
/AssignMessage При использовании политики VerifyAPIKey для аутентификации пользователя рекомендуется удалять параметр запроса apikey из сообщения запроса. Это необходимо для предотвращения передачи конфиденциальной информации о ключе на серверную часть.
6: Установка/получение переменных
В следующем примере используются три политики назначения сообщений:
- Создает три переменные потока в запросе со статическими значениями
- Динамически получает переменные потока во второй политике в потоке запросов.
- Устанавливает их в полезной нагрузке ответа
<!-- Policy #1: Set variables in the request --> <AssignMessage name="AM-set-varia>bles&<quot; !-- Create a variable named myAp>pSecr<et -- Assi>gnVariabl<e > Namem<yAppS>ecret/Nam<e > < Val>ue42/<Value /Assi>gnVar<iable !-- Create a variable named config.envi>ronme<nt -- Assi>gnVariabl<e > Nameconfig.e<nviro>nment/Nam<e > < Value>test/<Value /Assi>gnVar<iable !-- Create a variable named config.p>rotoc<ol -- Assi>gnVariabl<e > Nameconfi<g.pro>tocol/Nam<e > V<aluego>pher/<Value /Assi>g<nVariable /Ass>ignMessage
В первой политике элемент <AssignVariable> создаёт и задаёт три переменные в запросе. Каждый элемент <Name> задаёт имя переменной, а <Value> — её значение.
Вторая политика использует элемент <AssignVariable> для считывания значений и создает три новые переменные:
<!-- Policy #2: Get variables from the request --> <AssignMessage continueOnError="false" enabled="true" >nam<e="get-variables" AssignTo createNew="fals>e&q<uot; transport="http" type="request"/ !-- Get t>he <value of myApp>Secre<t an>d crea<te a >new v<ari>able, secre<t --> As<signV>a<riable> < Namesecret/Na>me < RefmyAppSecret/Ref Value0/Value /AssignVariable !-- Get the value of >con<fig.environmen>t and< cre>ate a new v<ariab>le, e<nvi>ronment -- Assig<nVar>iable< >Nameenv<ironme>nt/<Name Refcon>fig<.environment/Ref Valuedefault/Value /AssignVariable !-- Get the val>ue <of config.prot>ocol <and >create a< new >varia<ble>, protocol -- < Ass>ignVa<riabl>e N<amepro>toc<ol/Name Ref>con<fig.protocol/Ref Valu>edef<ault/Value /AssignVariab>l<e IgnoreUnre>solvedVariablestrue/IgnoreUnresolvedVariables /AssignMessage
Во второй политике элемент <Ref> ссылается на исходную переменную, а элементы <Name> определяют имена новых переменных. Если переменная, на которую ссылается элемент <Ref> недоступна, можно использовать значение, указанное элементом <Value> .
Чтобы опробовать этот набор политик:
- Добавьте политики №1 и №2 в поток запросов. Убедитесь, что политика №1 помещена перед политикой №2.
- Добавьте третью политику в поток ответов .
- Третья политика использует элемент
<Set>для добавления переменных в ответ. В следующем примере формируется полезная нагрузка XML в ответе, который Edge возвращает клиенту:<!-- Policy #3: Add variables to the response --> <AssignMessage continueOnError="false" enabled="true" name=&qu>ot;<put-em-in-t>he-payload" Di<splayNameput>-em<-in>-the-<payload/DisplayName Set Payload> conten<tType=&>quot;appl<icatio>n/xml&qu<ot; > wrappe<r > secret{<secret}/sec>ret c<onfig > environ<ment{env>ironment}/<environme>nt < pro>tocol{p<rotocol}>/prot<ocol > < /c>onf<ig /wrapper /Pa>yload < /Set IgnoreUnresolvedVa>ria<blestrue /IgnoreUnresolvedVariables AssignTo createNew=&>q<uot;false">; transport="http" type="response"/ /AssignMessage
Обратите внимание, что синтаксис доступа к переменным потока в
<Set>заключается в их заключении в фигурные скобки.Обязательно установите атрибут
contentTypeэлемента<Payload>на «application/xml». - Отправьте запрос на ваш API-прокси, например:
curl -vL https://ahamilton-eval-test.apigee.net/myproxy
При желании вы можете передать результаты через такую утилиту, как
xmllint, чтобы XML отображался в хорошо отформатированной структуре:curl -vL https://ahamilton-eval-test.apigee.net/myproxy | xmllint --format -
Текст ответа должен выглядеть следующим образом:
<wrapper> <secret>42</secret> <config> <environment>test</environment> <protocol>gopher</protocol> </config> </wrapper>
7. Получить заголовки ответа вызова службы
В следующем примере предположим, что политика ServiceCallout находится в запросе прокси-API, а ответ вызова содержит несколько заголовков с одинаковым именем ( Set-Cookie ). Если предположить, что переменная ответа вызова службы — это значение по умолчанию calloutResponse , следующая политика получает второе значение заголовка Set-Cookie .
<AssignMessage name="AM-Payload-from-SC-he>ade<r&q>uot; < Set Payload contentType="ap>plication/json" {"Cookies from Service Callout":" {calloutR<esponse.>hea<der.>Set<-Cookie.2}"} /Pa>yload < /Set IgnoreUnresolvedVa>ria<blestrue> /Igno<reUnresol>v<edVariables >AssignToresponse/AssignTo /AssignMessage
Чтобы вывести список всех значений заголовков, используйте следующую переменную:
{calloutResponse.header.Set-Cookie.values}Для каждого дочернего элемента в этом справочнике приведены дополнительные примеры. Ещё больше примеров можно найти в примере AssignMessage на GitHub.
Ссылка на дочерний элемент
В этом разделе описываются дочерние элементы <AssignMessage> .
<Add>
Добавляет информацию к запросу или ответу, указанному элементом <AssignTo> .
Элемент <Add> добавляет к сообщению новые свойства, отсутствующие в исходном сообщении. Чтобы изменить значения существующих свойств, используйте элемент <Set> .
| Значение по умолчанию | н/д |
| Необходимый? | Необязательный |
| Тип | Сложный тип |
| Родительский элемент | <AssignMessage> |
| Дочерние элементы | <FormParams><Headers><QueryParams> |
Элемент <Add> использует следующий синтаксис:
Синтаксис
<AssignMessage
continueOnError="[false|true]"
enabled="[true|false]"
> na<me=>"<;policy_na>me"<;
Add
FormParams
F>ormParam name=&<quot;formp>aram_name"<formparam_v>alue/<FormPar>am
< ...
/FormParams
> Headers
< Head>er name="h<eader_na>me&qu<ot;header_v>alue/He<ader
...
/Headers
Q>ueryParams
< QueryParam> name="que<ryparam_name>&qu<ot;q>u<eryparam_value>/QueryParam
...
/QueryParams
/Add
/AssignMessageПример 1
В следующем примере элемент <FormParams> используется для получения значений трех параметров строки запроса из исходного запроса и установки их в качестве параметров формы в запросе целевой конечной точки:
<AssignMessage name="AM-add-formpara>ms-<3&q>uot;
< Add
>FormPar<ams
FormParam name=>"username"{requ<est.queryp>aram.na<me}/FormParam
FormP>aram name="zip_code&quo<t;{request>.queryp<aram.zipCode}/FormParam
For>mParam name="default<_language&>quot;<{request.qu>ery<para>m.l<ang}/F>ormPa<ram
/For>mPa<rams
>/Ad<d
Remo>ve
<QueryPara>m<s/
/Remove
> AssignTorequest/AssignTo
/AssignMessageПример 2
В следующем примере элемент <Headers> используется для добавления заголовка partner-id к запросу, который будет отправлен в целевую конечную точку:
<AssignMessage name="AM-add-heade>rs-<1&q>uot;
< Add
> Head<ers
Header name=&q>uot;partner-id"{verifyapikey.VAK-1.devel<oper.ap>p.par<tner-id}>/He<ader>
< /Heade>rs
/A<dd
Assi>g<nTorequest/Ass>ignTo
/AssignMessageПример 3
В следующем примере элемент <QueryParams> используется для добавления к запросу одного параметра запроса со статическим значением:
<AssignMessage name="AM-add-querypara>ms-<1&q>uot;
< Add
Q>ueryPar<ams
QueryParam name>=&<quot;myPara>m&quo<t;42/QueryPa>ram<
> /Q<ueryPara>ms
/A<dd
Assi>g<nTorequest/Ass>ignTo
/AssignMessageВ этом примере в префлоу запроса используется <Add> . Если посмотреть на результаты в инструменте Trace , запрос к https://example-target.com/get превратится https://example-target.com/get?myParam=42 .
Дочерние элементы <Add> поддерживают динамическую подстановку строк, известную как шаблонизация сообщений .
<FormParams> (дочерний элемент <Add> )
Добавляет новые параметры формы в сообщение-запрос. Этот элемент не влияет на сообщение-ответ.
| Значение по умолчанию | н/д |
| Необходимый? | Необязательный |
| Тип | Массив элементов <FormParam> |
| Родительский элемент | <Add> |
| Дочерние элементы | <FormParam> |
Элемент <FormParams> использует следующий синтаксис:
Синтаксис
<AssignMessage continueOnError="[false|true]" enabled="[true|false]" > na<me=>"<;policy_na>me"<; Add FormParams F>ormParam name=&<quot;formp>aram_name"<formparam_v>alu<e/FormParam ... /FormParams AssignTo createNew="[true|false]&qu>ot; transport="http&<quot; > ty<pe=&>q<uot;[request|r>esponse]"destination_variable_name/AssignTo /Add /AssignMessage
Пример 1
В следующем примере к запросу добавляется один параметр формы («ответ») и статическое значение («42»):
<AssignMessage name="AM-add-formpara>ms-<1&q>uot;
< Add
>FormPar<ams
FormParam nam>e=<"answ>er&qu<ot;42/FormP>ara<m
> /<FormPara>ms
/A<dd
Assi>g<nTorequest/Ass>ignTo
/AssignMessageПример 2
В следующем примере получается значение параметра запроса name и добавляется к запросу как параметр формы, а затем удаляется параметр запроса:
<AssignMessage name="AM-Swap-QueryParam-to-FormPa>ram<s&q>uot;
< Add
FormParam n>ame="name"{requ<est.queryp>ara<m.na>me}</FormP>aram
< /Add
Remove
Que>ryP<aram na>m<e="name&q>uot;/
/Remove
/AssignMessageОбратите внимание, что в этом примере не указана цель с помощью <AssignTo> . Эта политика добавляет параметр только к запросу.
Пример 3
В следующем примере к запросу добавляется несколько параметров формы:
<AssignMessage name="AM-add-formpara>ms-<3&q>uot;
< Add
>FormPar<ams
FormParam name=>"username"{requ<est.queryp>aram.na<me}/FormParam
FormP>aram name="zip_code&quo<t;{request>.queryp<aram.zipCode}/FormParam
For>mParam name="default<_language&>quot;<{request.qu>ery<para>m.l<ang}/F>ormPa<ram
/For>mPa<rams
>/Ad<d
Remo>ve
<QueryPara>m<s/
/Remove
> AssignTorequest/AssignTo
/AssignMessageВ этом примере параметры строки запроса извлекаются из исходного запроса и добавляются как параметры формы с другими именами. Затем исходные параметры запроса удаляются. Apigee отправляет изменённый запрос в целевую конечную точку.
Вы можете использовать инструмент Trace для анализа потока. Вы увидите, что тело запроса содержит URL-кодированные данные формы, которые изначально были переданы в качестве параметров строки запроса:
username=nick&zip_code=90210&default_language=en
Использовать <FormParams> можно только при соблюдении следующих критериев:
- HTTP-глагол: POST
- Тип сообщения: Запрос
- Одно (или оба) из следующих:
- Данные формы: укажите какое-либо значение или "" (пустую строку). Например, при использовании
curlдобавьте-d ""к вашему запросу. - Заголовок
Content-Length: установите значение 0 (если в исходном запросе нет данных; в противном случае — текущая длина в байтах). Например, с помощьюcurlдобавьте к запросу-H "Content-Length: 0".
- Данные формы: укажите какое-либо значение или "" (пустую строку). Например, при использовании
Например:
curl -vL -X POST -d "" -H "Content-Type: application/x-www-form-urlencoded" https://ahamilton-eval-test.apigee.net/am-test
При добавлении <FormParams> Edge устанавливает заголовок Content-Type запроса на «application/x-www-form-urlencoded» перед отправкой сообщения целевой службе.
<Headers> (дочерний элемент <Add> )
Добавляет новые заголовки к указанному запросу или ответу, который указан элементом <AssignTo> .
| Значение по умолчанию | н/д |
| Необходимый? | Необязательный |
| Тип | Массив элементов <Header> |
| Родительский элемент | <Add> |
| Дочерние элементы | <Header> |
Элемент <Headers> использует следующий синтаксис:
Синтаксис
<AssignMessage
continueOnError="[false|true]"
enabled="[true|false]"
> na<me=>"<;policy>_name&q<uot;
Add
Headers
> Header <name=&q>uot;header_name<"he>ade<r_va>l<ue/Header
> ...
/Headers
/Add
/AssignMessageПример 1
В следующем примере к сообщению-запросу добавляется заголовок partner-id , а этому заголовку присваивается значение переменной потока verifyapikey.VAK-1.developer.app.partner-id .
<AssignMessage name="AM-add-heade>rs-<1&q>uot;
< Add
> Head<ers
Header name=&q>uot;partner-id"{verifyapikey.VAK-1.devel<oper.ap>p.par<tner-id}>/He<ader>
< /Heade>rs
/A<dd
Assi>g<nTorequest/Ass>ignTo
/AssignMessage <QueryParams> (дочерний элемент <Add> )
Добавляет новые параметры запроса к запросу. Этот элемент не влияет на ответ.
| Значение по умолчанию | н/д |
| Необходимый? | Необязательный |
| Тип | Массив элементов <QueryParam> |
| Родительский элемент | <Add> |
| Дочерние элементы | <QueryParam> |
Элемент <QueryParams> использует следующий синтаксис:
Синтаксис
<AssignMessage
continueOnError="[false|true]"
enabled="[true|false]"
> na<me=>"<;policy_nam>e"<
Add
QueryParams
Que>ryParam name=&qu<ot;querypar>am_name"qu<eryparam_val>ue/<Quer>y<Param
..>.
/QueryParams
/Add
/AssignMessageПример 1
В следующем примере к запросу добавляется параметр запроса «myParam» и ему присваивается значение «42»:
<AssignMessage name="AM-add-querypara>ms-<1&q>uot;
< Add
Q>ueryPar<ams
QueryParam name>=&<quot;myPara>m&quo<t;42/QueryPa>ram<
> /Q<ueryPara>ms
/A<dd
Assi>g<nTorequest/Ass>ignTo
/AssignMessage Использовать <QueryParams> можно только при соблюдении следующих критериев:
- HTTP-глагол: GET
- Тип сообщения: Запрос
Кроме того, параметры запроса можно задать только в том случае, если атрибут type элемента <AssignTo> представляет собой сообщение-запрос. Установка этих параметров в ответе не имеет никакого эффекта.
Если вы определяете пустой массив параметров запроса в своей политике ( <Add><QueryParams/></Add> ), политика не добавляет никаких параметров запроса. Это равносильно пропуску <QueryParams> .
<AssignTo>
Определяет, к какому объекту применяется политика AssignMessage. Возможные варианты:
- Сообщение запроса:
request, полученный API-прокси - Ответное сообщение:
responseвозвращенный целевым сервером. - Пользовательское сообщение: Пользовательский объект запроса или ответа.
Обратите внимание, что в некоторых случаях невозможно изменить объект, к которому применяется политика AssignMessage. Например, нельзя использовать <Add> или <Set> для добавления или изменения параметров запроса ( <QueryParams> ) или параметров формы ( <FormParams> ) в ответе. Изменять можно только параметры запроса и параметры формы в запросе.
| Значение по умолчанию | н/д |
| Необходимый? | Необязательный |
| Тип | Нить |
| Родительский элемент | <AssignMessage> |
| Дочерние элементы | Никто |
Если элемент <AssignTo> не указан или указан, но не указано текстовое значение элемента, политика применяется к запросу или ответу по умолчанию, в зависимости от того <AssignTo> где политика выполняется. Если политика выполняется в потоке запросов, она влияет на сообщение запроса. Если она выполняется в потоке ответов, политика по умолчанию влияет на ответ.
Элемент <AssignTo> использует следующий синтаксис:
Синтаксис
<AssignMessage continueOnError="[false|true]" enabled="[true|false]" > na<me="policy_name" AssignTo createNew="[true|false]" transp>ort="http" <type=&quo>t<;[request|resp>onse]"destination_variable_name/AssignTo /AssignMessage
Пример 1
В следующем примере указано, что целью является исходный запрос, который будет отправлен в целевую конечную точку:
<AssignMessage name="assign>t<o-1" !-- DO NOT >do <this -- AssignTo createNew="false" transport=&q>u<ot;http" >type="request"/ /AssignMessage
Пример 2
В следующем примере создается новый объект запроса:
<AssignMessage name="AM-assign>to-2<" AssignTo createNew="true" transport=&>quot;http" <type=&quo>t;<request"N>ameOfNewMessage/AssignTo /AssignMessage
При создании нового объекта запроса или ответа другие элементы политики AssignMessage (такие как <Add> , <Set> и <Copy> ) действуют на этот новый объект запроса.
Вы можете получить доступ к новому объекту запроса в других политиках позже в потоке или отправить новый объект запроса внешней службе с политикой ServiceCallout .
Пример 3
В следующем примере создается новый объект запроса с именем «MyRequestObject»:
<AssignMessage name="assign>to-<2" AssignTo createNew="true" transport=&"http" ty&pe="req>u<est"gt;My>RequestObjectlt;/AssignTo /AssignMessage
При создании нового объекта запроса или ответа другие элементы политики AssignMessage (такие как <Add> , <Set> и <Copy> ) действуют на этот новый объект запроса.
Вы можете получить доступ к новому объекту запроса в других политиках позже в потоке или отправить новый объект запроса внешней службе с политикой ServiceCallout .
В следующей таблице описаны атрибуты <AssignTo> :
| Атрибут | Описание | Необходимый? | Тип |
|---|---|---|---|
createNew | Определяет, создает ли эта политика новое сообщение при назначении значений. Если значение равно «true», политика создаёт новую переменную указанного Если «ложь», то политика реагирует одним из двух способов:
Если
| Необязательный | Булевое значение |
transport | Указывает тип транспорта для типа сообщения-запроса или ответа. Значение по умолчанию — «http» (единственное поддерживаемое значение). | Необязательный | Нить |
type | Указывает тип нового сообщения, если createNew имеет значение «true». Допустимые значения: «request» или «response».Если этот атрибут пропущен, Edge создает либо запрос, либо ответ в зависимости от того, где в потоке выполняется эта политика. | Необязательный | Нить |
<AssignVariable>
Присваивает значение переменной потока. Если переменная потока не существует, метод <AssignVariable> создаёт её.
| Значение по умолчанию | н/д |
| Необходимый? | Необязательный |
| Тип | Сложный тип |
| Родительский элемент | <AssignMessage> |
| Дочерние элементы | <Name> (обязательно)<Ref><Template><Value> |
Значение, которое вы присваиваете переменной потока, может быть одним из следующих:
- Строка литералов: используйте дочерний элемент
<Value>, чтобы указать строковое значение литералов для переменной потока. - Переменная потока: используйте дочерний элемент
<Ref>, чтобы указать значение существующей переменной потока для целевой переменной потока. Полный список переменных потока, которые можно использовать в качестве источника, см. в разделе «Справочник по переменным потока» . - Шаблон сообщения: используйте дочерний элемент
<Template>, чтобы указать шаблон сообщения для интерполяции, чтобы получить значение для помещения в переменную потока назначения.
Элемент <AssignVariable> использует следующий синтаксис:
Синтаксис
<AssignMessage continueOnError="[false|true]" enabled="[true|false]" > na<me="polic>y_nam<e&qu>ot; Assign<Varia>ble < >Namevariable_na<me/N>ame < Refso>urce_variable/Re<f Tem>platemessage<_template/Template or Te><mplate re>f=<9;tem>plate_variable<'/>Tem<plate Value>v<ariable_value/>Value /AssignVariable /AssignMessage
Используйте элемент <Ref> для указания исходной переменной. Если переменная, на которую ссылается элемент <Ref> недоступна, Edge использует значение, указанное элементом <Value> . Если вы определяете <Template> , он имеет приоритет над другими дочерними элементами.
Пример 1
В следующем примере новой переменной myvar присваивается буквальное значение «42»:
<AssignMessage name="assignvariab>le-<1" Assi>gnVar<iabl>e < Name>myvar</Name> < Val>ue4<2/Value /Assi>g<nVariable /Ass>ignMessage
Пример 2
В следующем примере значение переменной потока request.header.user-agent присваивается переменной потока назначения myvar , а значение параметра запроса country — переменной потока назначения Country :
<AssignMessage name="assignvariab>le-<2" Assi>gnVar<iabl>e < Name>myvar</Na>me Refrequest.header.<user>-agen<t/Ref> ValueE<rrorOn>Cop<y/Value /Assi>gnV<ariable Assi>gnVar<iabl>e N<ameCo>untry</Na>me Refrequest.querypar<am.c>ountr<y/Ref> ValueE<rrorOn>Cop<y/Value /Assi>g<nVariable /Ass>ignMessage
Если какое-либо из назначений не удается, Edge вместо этого присваивает значение «ErrorOnCopy» целевой переменной потока.
Если переменные потока myvar или Country не существуют, <AssignVariable> создает их.
Пример 3
В следующем примере дочерний элемент <Template> используется для объединения двух контекстных переменных со строкой символов (дефисом) между ними:
<AssignMessage name='AV-via-templat>e-1<' IgnoreUnresolvedV>ariab<lesfalse/IgnoreUnresolvedV>ari<ables Assign>Varia<ble<>/span> Namemy_destination_<varia>ble/N<ame > Value<BADDBE>EF/Va<lue >Template{system.uuid}-{me<ssageid}/>Tem<plate /Assign>V<ariable /Assig>nMessage
Обычно элемент <AssignVariable> используется для установки значения по умолчанию для параметра запроса, заголовка или другого значения, которое может быть передано вместе с запросом. Это делается с помощью комбинации дочерних элементов <Ref> и <Value> . Подробнее см. в примерах для <Ref> .
<Name> (дочерний элемент <AssignVariable> >)
Указывает имя целевой переменной потока (например, переменной, значение которой задаётся политикой AssignMessage). Если переменная, указанная в <AssignVariable> , не существует, политика создаёт её с этим именем.
| Значение по умолчанию | н/д |
| Необходимый? | Необходимый |
| Тип | Нить |
| Родительский элемент | <AssignVariable> |
| Дочерние элементы | Никто |
Элемент <Name> использует следующий синтаксис:
Синтаксис
<AssignMessage continueOnError="[false|true]" enabled="[true|false]" > na<me="polic>y_nam<e&qu>ot; Assign<Varia>ble< Namevariab>l<e_name/Name >/AssignVariable /AssignMessage
Пример 1
В следующем примере переменная назначения указывается как myvar и ей присваивается буквальное значение «42»:
<AssignMessage name="assignvariab>le-<1" Assi>gnVar<iabl>e < Name>myvar</Name> < Val>ue4<2/Value /Assi>g<nVariable /Ass>ignMessage
Если myvar не существует, <AssignVariable> создает его.
<Ref> (дочерний элемент <AssignVariable> )
Указывает источник назначения как переменную потока. Переменная потока может быть одной из предопределённых переменных потока (перечисленных в справочнике переменных потока ) или созданной вами пользовательской переменной потока.
Значение <Ref> всегда интерпретируется как переменная потока; в качестве значения нельзя указать литеральную строку. Чтобы задать литеральное строковое значение, используйте элемент <Value> .
| Значение по умолчанию | н/д |
| Необходимый? | Необязательный |
| Тип | Нить |
| Родительский элемент | <AssignVariable> |
| Дочерние элементы | Никто |
При указании переменной потока с помощью <Ref> опускайте скобки "{}", которые обычно используются для ссылки на переменную потока. Например, чтобы установить значение новой переменной равным значению переменной потока client.host :
Do this (no brackets): <Ref>client.host</Ref> Do NOT do this (brackets): <Ref>{client.host}</Ref>
Чтобы определить значение по умолчанию для целевой переменной потока, используйте <Value> в сочетании с <Ref> . Если переменная потока, указанная <Ref> , не существует, не может быть прочитана или равна NULL, Edge присваивает значение <Value> целевой переменной потока.
Элемент <Ref> использует следующий синтаксис:
Синтаксис
<AssignMessage continueOnError="[false|true]" enabled="[true|false]" > na<me="polic>y_nam<e&qu>ot; Assign<Varia>ble < >Namevariable_na<me/N>ame< Refsource_>v<ariable/Ref >/AssignVariable /AssignMessage
Пример 1
В следующем примере значение переменной потока request.header.user-agent присваивается целевой переменной потока myvar , а значение параметра запроса country — переменной Country :
<AssignMessage name="assignvariab>le-<4" Assi>gnVar<iabl>e < Name>myvar</Na>me Refrequest.header.<user>-ag<ent/Ref /Assi>gnV<ariable Assi>gnVar<iabl>e N<ameCo>untry</Na>me Refrequest.querypar<am.c>oun<try/Ref /Assi>g<nVariable /Ass>ignMessage
В этом примере Edge не имеет значения по умолчанию (или резервного значения) ни для одного из назначений.
Пример 2
В следующем примере значение переменной потока request.header.user-agent присваивается целевой переменной потока myvar , а значение параметра запроса country — переменной Country :
<AssignMessage name="assignvariab>le-<2" Assi>gnVar<iabl>e < Name>myvar</Na>me Refrequest.header.<user>-agen<t/Ref> ValueE<rrorOn>Cop<y/Value /Assi>gnV<ariable Assi>gnVar<iabl>e N<ameCo>untry</Na>me Refrequest.querypar<am.c>ountr<y/Ref> ValueE<rrorOn>Cop<y/Value /Assi>g<nVariable /Ass>ignMessage
В этом примере, если значения переменной потока request.header.user-agent или параметра запроса Country равны нулю, нечитаемы или имеют неправильный формат, Edge присваивает новым переменным значение «ErrorOnCopy».
Пример 3
Типичный пример использования <AssignVariable> — установка значения по умолчанию для параметра запроса, заголовка или другого значения, которое может быть передано вместе с запросом. Например, вы создаёте прокси-сервер API погоды, где запрос принимает один параметр запроса с именем «w». Этот параметр содержит идентификатор города, для которого вы хотите получить данные о погоде. URL-адрес запроса имеет вид:
http://myCO.com/v1/weather/forecastrss?w=city_ID
Чтобы определить значение по умолчанию для «w», создайте политику AssignMessage следующим образом:
<AssignMessage continueOnError="false" enabled="true" nam>e=&<quot;assignvariable-3" AssignTo createNew="fals>e&q<uot; transport="http>" <type="request"/ > I<gnoreUnresolve>dVari<able>strue /IgnoreUnres<olved>Varia<ble>s AssignVariable < N>amere<quest>.querypa<ram.w/>Nam<e Refreques>t<.queryparam.w/>Ref Value12797282/Value /AssignVariable /AssignMessage
В этом примере <AssignVariable> получает значение request.queryparam.w и присваивает его себе. Если переменная потока равна null, что означает, что параметр запроса «w» был пропущен в запросе, то в этом примере используется значение по умолчанию из элемента <Value> . Следовательно, вы можете сделать запрос к этому API-прокси, опустив параметр запроса «w»:
http://myCO.com/v1/weather/forecastrss
...и API-прокси по-прежнему возвращает допустимый результат.
В отличие от использования <Value> , значение <Ref> должно быть переменной потока, например, свойством request , response или target объекта. Значение также может быть созданной вами пользовательской переменной потока.
Если указать переменную потока, которая не существует для значения <Ref> , а значение <IgnoreUnresolvedVariables> равно «true», Edge выдаст ошибку.
<Template> (дочерний элемент <AssignVariable> )
Задаёт шаблон сообщения . Шаблон сообщения позволяет выполнять подстановку строк переменных при выполнении политики и может комбинировать литеральные строки с именами переменных, заключёнными в фигурные скобки. Кроме того, шаблоны сообщений поддерживают такие функции , как экранирование и преобразование регистра.
Используйте атрибут ref для указания переменной потока, значением которой является шаблон сообщения. Например, вы можете сохранить шаблон сообщения как настраиваемый атрибут в приложении разработчика . Когда Edge идентифицирует приложение разработчика после проверки ключа API или токена безопасности (через дополнительную политику), элемент <AssignVariable> может использовать шаблон сообщения из настраиваемого атрибута приложения, который доступен как переменная потока в политике безопасности.
| Значение по умолчанию | н/д |
| Необходимый? | Необязательный |
| Тип | Нить |
| Родительский элемент | <AssignVariable> |
| Дочерние элементы | Никто |
Элемент <Template> использует следующий синтаксис:
Синтаксис
<AssignMessage continueOnError="[false|true]" enabled="[true|false]" > na<me="polic>y_nam<e" > AssignVariabl<e Tem>platemessage<_template/Template or Te><mplate re>f=&<#39;template_va>r<iable'/Tem>plate /AssignVariable /AssignMessage
Пример 1
В следующем примере синтаксис шаблона сообщений используется для объединения двух контекстных переменных со строкой символов (дефисом) между ними:
<AssignMessage name='AV-via-templat>e-1<' IgnoreUnresolvedV>ariab<lesfalse/IgnoreUnresolvedV>ari<ables Assign>Varia<ble<>/span> Namemy_destination_<varia>ble/N<ame > Value<BADDBE>EF/Va<lue >Template{system.uuid}-{me<ssageid}/>Tem<plate /Assign>V<ariable /Assig>nMessage
Пример 2
В следующем примере задаётся переменная потока, значение которой — предопределённый шаблон сообщения. Используйте этот параметр, если хотите внедрить предопределённый шаблон во время выполнения, не изменяя политику:
<AssignMessage name='AV-via-template-indirec>tly<39; IgnoreUnresolvedV>ariab<lesfalse/IgnoreUnresolvedV>ari<ables Assign>Varia<ble<>/span> Namemy_destination_<varia>ble/N<ame > Value<BADDBE>EF/Va<lue Template ref='my_templat>e_v<ariable'/ > </AssignVariabl>e /AssignMessage
Пример 3
В следующем примере задаются переменная потока и текстовое значение. В этом случае, если указанная переменная не равна NULL, это значение используется в качестве шаблона. Если указанное значение равно NULL, то в качестве шаблона используется текстовое значение (в данном случае {system.uuid}-{messageid} ). Этот шаблон полезен для предоставления «переопределяющего» значения, когда в некоторых случаях требуется переопределить шаблон по умолчанию (текстовую часть) значениями, устанавливаемыми динамически. Например, условный оператор может извлечь значение из сопоставления «ключ-значение» и установить это значение для указанной переменной:
<AssignMessage name='AV-template-with-fallb>ack<' IgnoreUnresolvedV>ariab<lesfalse/IgnoreUnresolvedV>ari<ables Assign>Varia<ble<>/span> Namemy_destination_<varia>ble/N<ame > Value<BADDBE>EF/Va<lue Template ref='>my_variable'{system.u<uid}-{mes>sag<eid}/Template > </AssignVariabl>e /AssignMessage
<Value> (дочерний элемент <AssignVariable> )
Определяет значение целевой переменной потока, заданное с помощью <AssignVariable> . Значение всегда интерпретируется как строковый литерал; переменную потока нельзя использовать в качестве значения, даже если её заключить в скобки ("{}"). Чтобы использовать переменную потока, используйте <Ref> .
| Значение по умолчанию | н/д |
| Необходимый? | Необязательный |
| Тип | Нить |
| Родительский элемент | <AssignVariable> |
| Дочерние элементы | Никто |
При использовании в сочетании с элементом <Ref> <Value> действует как значение по умолчанию (или резервное). Если <Ref> не указан, неразрешим или равен NULL, используется значение <Value> .
Элемент <Value> использует следующий синтаксис:
Синтаксис
<AssignMessage continueOnError="[false|true]" enabled="[true|false]" > na<me="polic>y_nam<e&qu>ot; Assign<Varia>ble < Na>mevariable_nam<e/Name> < Valuevariable>_<value/Value >/AssignVariable /AssignMessage
Пример 1
В следующем примере переменной потока назначения myvar присваивается буквальное значение «42»:
<AssignMessage name="assignvariab>le-<1" Assi>gnVar<iabl>e < Name>myvar</Name> < Val>ue4<2/Value /Assi>g<nVariable /Ass>ignMessage
Пример 2
В следующем примере значение переменной потока request.header.user-agent присваивается переменной потока myvar , а значение параметра запроса country — переменной Country :
<AssignMessage name="assignvariab>le-<2" Assi>gnVar<iabl>e < Name>myvar</Na>me Refrequest.header.<user>-agen<t/Ref> ValueE<rrorOn>Cop<y/Value /Assi>gnV<ariable Assi>gnVar<iabl>e N<ameCo>untry</Na>me Refrequest.querypar<am.c>ountr<y/Ref> ValueE<rrorOn>Cop<y/Value /Assi>g<nVariable /Ass>ignMessage
Если какое-либо из назначений не удается, <AssignVariable> вместо этого присваивает значение «ErrorOnCopy» целевой переменной потока.
<Copy>
Копирует значения из сообщения, указанного атрибутом source , в сообщение, указанное элементом <AssignTo> . Если целевой объект не указан с помощью <AssignTo> , эта политика копирует значения в запрос или ответ, в зависимости от того, где в потоке выполняется эта политика.
| Значение по умолчанию | н/д |
| Необходимый? | Необязательный |
| Тип | Нить |
| Родительский элемент | <AssignMessage> |
| Дочерние элементы | <FormParams><Headers><Path><Payload><QueryParams><ReasonPhrase><StatusCode><Verb><Version> |
Если под элементом <Copy> не указано ни одного дочернего элемента, то будут скопированы все части указанного исходного сообщения.
Элемент <Copy> использует следующий синтаксис:
Синтаксис
<AssignMessage
continueOnError="[false|true]"
enabled="[true|false]"
> name<="policy_name"
Co>py so<urce="[request|response]&qu<ot;
!--> Can also <be an empt>y array< (FormParams/) -->
FormP>arams
For<mParam nam>e="formpar<am_name&quo>t;for<mparam_value/FormParam
...<
/Fo>rmParams
< !-- >Can als<o be an empty array (Head>ers/) --><
He>aders
Hea<der name>=&quo<t;he>ader_name&qu<ot;he>ader_<value/H>eader
<...
>/Head<ers
Path[false|true]/Path
< Payload[fa>lse|true]/<Payload
> !-- Ca<n also be an empty array (QueryPa>rams/) -->
< QueryPara>ms
QueryP<aram name=&q>uot;q<ueryparam_na>me"quer<yparam_value/>Query<Param
> ...
/Q<ueryParams<>/span>
R<easo>nPhrase[fals<e|tru>e]/Re<asonPhr>ase
Stat<usCode[f>als<e|tru>e]/<StatusCode
Verb[false|true]/Verb<
> Version[f>als<e|true]/Version
/Copy
!-- Used as the destination for the Copy values --
A>ssignTo createNew="[<true|fals>e<]" transp>ort="http"
type="[request|response]"destination_variable_name/AssignTo
/AssignMessage
Пример 1
В следующем примере заголовок, три параметра формы, путь и все параметры запроса копируются из сообщения- request в новый пользовательский запрос с именем newRequest :
<AssignMessage name="AM-co>py-<1" AssignTo createNew="true" transport=&>quot;http&<quot; typ>e=&<quot;request"new>Reque<st/Assi>gnTo <Copy source="request&qu>ot; < Heade>rs < Header> name=&<quot;Header_Name_1"/ /Head>ers < FormParams FormParam name=&q>uot;For<m_Param_Name_1"/ FormPar>am na<me="Fo>rm_Pa<ram_>Name<_2&qu>ot;/ < FormPa>ram< name>=<"Form_Par>am_Name_3"/ /FormParams Pathtrue/Path QueryParams/ /Copy /AssignMessage
Поскольку такие элементы, как <Payload> и <Verb> отсутствуют, политика не копирует эти части сообщения.
Пример 2
В следующем примере сначала удаляется все из существующего response сообщения, а затем копируются все значения из другого сообщения с именем secondResponse в response сообщение:
<AssignMessage name='AM-Copy-Respo>nse<' AssignTo createNew="false" transport=&quo>t;http&q<uot; type>=&q<uot;response"response/AssignTo !>-- <first r>emo<ve any existing values -- Remove/ !-- then copy eve>ryt<hing from the designated mess>a<ge -- Copy s>ource="secondResponse"/ /AssignMessage
Элемент <Copy> имеет один атрибут:
| Атрибут | Описание | Необходимый? | Тип |
|---|---|---|---|
| источник | Указывает исходный объект копии.
| Необязательный | Нить |
<FormParams> (дочерний элемент <Copy> )
Копирует параметры формы из запроса, указанного атрибутом source элемента <Copy> , в запрос, указанный элементом <AssignTo> . Этот элемент не влияет на ответ.
| Значение по умолчанию | н/д |
| Необходимый? | Необязательный |
| Тип | Массив элементов <FormParam> или пустой массив |
| Родительский элемент | <Copy> |
| Дочерние элементы | <FormParam> |
Элемент <FormParams> использует следующий синтаксис:
Синтаксис
<AssignMessage continueOnError="[false|true]" enabled="[true|false]" > na<me="policy_name" Co>py so<urce="[request|response]&qu<ot; !--> Can also <be an empt>y array< (FormParams/) --> FormP>arams For<mParam nam>e="formpar<am_name&quo>t;f<ormpa>r<am_value/FormP>aram ... /FormParams /Copy /AssignMessage
Пример 1
В следующем примере копируется один параметр формы из запроса в пользовательский запрос «MyCustomRequest»:
<AssignMessage name="copy-formpara>ms-<1" Copy source>=&quo<t;request&>quot; < FormParams FormPa>ram name="par<amName&quo>t;For<m param val>ue <1/For>mPa<ram /FormParams /Copy AssignTo createNew="tr>ue" transp<ort=">;<http" typ>e="request"MyCustomRequest/AssignTo /AssignMessage
Пример 2
В следующем примере все параметры формы копируются в пользовательский запрос «MyCustomRequest»:
<AssignMessage name="copy-formpara>ms-<2" Copy source>=&quo<t;request&q>uot<; > Fo<rmParams/ /Copy AssignTo createNew="true" t>ransport="<http">;< type="re>quest"MyCustomRequest/AssignTo /AssignMessage
Пример 3
В следующем примере три параметра формы копируются в пользовательский запрос «MyCustomRequest»:
<AssignMessage name="copy-formpara>ms-<3" Copy source>=&quo<t;request&>quot; < FormParams FormPara>m name=<"paramName1"/ > FormP<aram name="paramName2&q>uot;/< Form>Par<am na>me=<"paramName3"/ /FormParams /Copy AssignT>o createNew=&qu<ot;true&q>u<ot; transport=>"http" type="request"MyCustomRequest/AssignTo /AssignMessage
Пример 4
Если имеется несколько параметров формы с одинаковым именем, используйте следующий синтаксис:
<AssignMessage name="copy-formpara>ms-<4" Copy source>=&quo<t;request&>quot; < FormParams >FormPar<am name="f1&quo>t;/ < FormParam name=&quo>t;f2&<quot;/ > F<ormPa>ram< name="f3.2"/ /FormParams /Copy AssignT>o createNew=&qu<ot;true&q>u<ot; transport=>"http" type="request"MyCustomRequest/AssignTo /AssignMessage
В этом примере копируются «f1», «f2» и второе значение «f3». Если у «f3» только одно значение, оно не копируется.
Использовать <FormParams> можно только при соблюдении следующих критериев:
- HTTP-глагол: POST
- Тип сообщения: Ответ
- Одно (или оба) из следующих:
- Данные формы: укажите какое-либо значение или "" (пустую строку). Например, при использовании
curlдобавьте-d ""к вашему запросу. - Заголовок
Content-Length: установите значение 0 (если в исходном запросе нет данных; в противном случае — текущая длина). Например, с помощьюcurlдобавьте-H "Content-Length: 0"к вашему запросу.
- Данные формы: укажите какое-либо значение или "" (пустую строку). Например, при использовании
При копировании <FormParams> , <Copy> устанавливает Content-Type сообщения на «application/x-www-form-urlencoded» перед отправкой сообщения целевой службе.
<Headers> (дочерний элемент <Copy> >)
Копирует заголовки HTTP из сообщения запроса или ответа, указанного атрибутом source элемента <Copy> , в сообщение запроса или ответа, указанное элементом <AssignTo> .
| Значение по умолчанию | н/д |
| Необходимый? | Необязательный |
| Тип | Массив элементов <Header> или пустой массив |
| Родительский элемент | <Copy> |
| Дочерние элементы | <Header> |
Элемент <Headers> использует следующий синтаксис:
Синтаксис
<AssignMessage continueOnError="[false|true]" enabled="[true|false]" > na<me="policy_name" Co>py so<urce="[request|response]&qu<ot; >!-- Can al<so be a>n empty< array (Headers/) --> > Headers < H>eader name=&quo<t;header>_na<me&qu>o<t;header_value>/Header ... /Headers /Copy /AssignMessage
Пример 1
В следующем примере заголовок user-agent копируется из запроса в новый, пользовательский объект запроса:
<AssignMessage name="copy-heade>rs-<1" Copy source>=&quo<t;reque>st"<; Headers Heade>r nam<e=">use<r-age>nt&<quot;/ /Headers /Copy AssignTo createNew="tr>ue" transp<ort=">;<http" typ>e="request"MyCustomRequest/AssignTo /AssignMessage
Пример 2
Чтобы скопировать все заголовки, используйте пустой элемент <Headers> , как показано в следующем примере:
<AssignMessage name="copy-heade>rs-<2" Copy source>=&quo<t;reques>t&q<uot;<>/span> < Headers/ /Copy AssignTo createNew="true" t>ransport="<http">;< type="re>quest"MyCustomRequest/AssignTo /AssignMessage
Пример 3
Если имеется несколько заголовков с одинаковым именем, используйте следующий синтаксис:
<AssignMessage name="copy-heade>rs-<3" Copy source>=&quo<t;reque>st"<; Headers > Head<er name="h1&>quot;/ < Header name=&>quot;<h2">/ < >Hea<der name="h3.2"/ /Headers /Copy AssignT>o createNew=&qu<ot;true&q>u<ot; transport=>"http" type="request"MyCustomRequest/AssignTo /AssignMessage
В этом примере копируются поля "h1", "h2" и второе значение поля "h3". Если поле "h3" имеет только одно значение, оно не копируется.
<Path> (дочерний элемент <Copy> >)
Определяет, следует ли копировать путь из исходного запроса в целевой. Этот элемент не влияет на ответ.
Если «true», эта политика копирует путь из сообщения-запроса, указанного атрибутом source элемента <Copy> , в сообщение-запрос, указанное элементом <AssignTo> .
| Значение по умолчанию | ЛОЖЬ |
| Необходимый? | Необязательный |
| Тип | Булевое значение |
| Родительский элемент | <Copy> |
| Дочерние элементы | Никто |
Элемент <Path> использует следующий синтаксис:
Синтаксис
<AssignMessage
continueOnError="[false|true]"
enabled="[true|false]"
> na<me="policy_name"
Co>py so<urce>="[requ<est|r>esp<onse]>&<quot;
Path>[false|true]/Path
/Copy
/AssignMessageПример 1
В следующем примере показано, что политика AssignMessage должна копировать путь из исходного запроса в новый, пользовательский объект запроса:
<AssignMessage name="copy-pa>th-<1" Copy source>=&quo<t;re>ques<t&quo>t; < P>ath<true/Path /Copy AssignTo createNew="true" t>ransport="<http">;< type="re>quest"MyCustomRequest/AssignTo /AssignMessage
Использовать <Path> можно только при соблюдении следующих критериев:
- Тип сообщения: Запрос
<Payload> (дочерний элемент <Copy> )
Определяет, следует ли копировать полезную нагрузку из источника в пункт назначения. Источник и пункт назначения могут быть запросами или ответами.
Если значение равно «true», эта политика копирует полезную нагрузку из сообщения, указанного атрибутом source элемента <Copy> , в сообщение, указанное элементом <AssignTo> .
| Значение по умолчанию | ЛОЖЬ |
| Необходимый? | Необязательный |
| Тип | Булевое значение |
| Родительский элемент | <Copy> |
| Дочерние элементы | Никто |
Элемент <Payload> использует следующий синтаксис:
Синтаксис
<AssignMessage continueOnError="[false|true]" enabled="[true|false]" > na<me="policy_name" Co>py so<urce=&q>uot;[request<|respons>e]&<quot;> < Payload[fa>lse|true]/Payload /Copy /AssignMessage
Пример 1
В следующем примере параметру <Payload> присваивается значение «true», чтобы полезная нагрузка запроса копировалась из запроса в ответ:
<AssignMessage name="AM-copy-paylo>ad-<1" Copy source>=&quo<t;reque>st&q<uot; > Pa<yload>tru<e/Payloa>d /Cop<y Assig>n<Toresponse/Ass>ignTo /AssignMessage
<QueryParams> (дочерний элемент <Copy> )
Копирует параметры строки запроса из запроса, указанного атрибутом source элемента <Copy> , в запрос, указанный элементом <AssignTo> . Этот элемент не влияет на ответ.
| Значение по умолчанию | н/д |
| Необходимый? | Необязательный |
| Тип | Массив элементов <QueryParam> или пустой массив |
| Родительский элемент | <QueryParam> |
| Дочерние элементы | Никто |
Элемент <QueryParams> использует следующий синтаксис:
Синтаксис
<AssignMessage continueOnError="[false|true]" enabled="[true|false]" > na<me="policy_name" Co>py so<urce="[request|response]&qu<ot; !-- >Can also b<e an empty >array (<QueryParams/) --> QueryPar>ams QueryP<aram name=&>quot;queryparam<_name"q>uer<ypara>m<_value/QueryPa>ram ... /QueryParams /Copy /AssignMessage
Пример 1
В следующем примере параметр запроса «my_param» копируется из запроса в новый, пользовательский объект запроса:
<AssignMessage name="copy-querypara>ms-<1" Copy source>=&quo<t;request&q>uot; < QueryParams QueryPa>ram n<ame="my>_pa<ram&q>uot<;/ /QueryParams /Copy AssignTo createNew="tr>ue" transp<ort=">;<http" typ>e="request"MyCustomRequest/AssignTo /AssignMessage
Пример 2
В следующем примере все параметры запроса копируются в новый пользовательский объект запроса:
<AssignMessage name="copy-querypara>ms-<2" Copy source>=&quo<t;request&qu>ot;< >Que<ryParams/ /Copy AssignTo createNew="true" t>ransport="<http">;< type="re>quest"MyCustomRequest/AssignTo /AssignMessage
Пример 3
Если имеется несколько параметров запроса с одинаковым именем, используйте следующий синтаксис:
<AssignMessage name="copy-querypara>ms-<3" Copy source>=&quo<t;request&q>uot; < QueryParams Qu>eryPara<m name="qp1">/ < QueryParam name="q>p2&qu<ot;/ Q>uer<yPara>m n<ame="qp3.2"/ /QueryParams /Copy AssignT>o createNew=&qu<ot;true&q>u<ot; transport=>"http" type="request"MyCustomRequest/AssignTo /AssignMessage
В этом примере копируются «qp1», «qp2» и второе значение «qp3». Если у «qp3» только одно значение, оно не копируется.
Использовать <QueryParams> можно только при соблюдении следующих критериев:
- HTTP-глагол: GET
- Тип сообщения: Запрос
<ReasonPhrase> (дочерний элемент <Copy> )
Определяет, следует ли копировать фразу-причину из исходного ответа в целевой ответ. Этот элемент не влияет на запрос.
If "true", this policy copies the ReasonPhrase from the response specified by the <Copy> element's source attribute to the response specified by the <AssignTo> element.
| Значение по умолчанию | ЛОЖЬ |
| Необходимый? | Необязательный |
| Тип | Булевое значение |
| Parent Element | <Copy> |
| Child Elements | Никто |
The <ReasonPhrase> element uses the following syntax:
Syntax
<AssignMessage
continueOnError="[false|true]"
enabled="[true|false]"
> na<me="policy_name"
Co>py so<urce="[>request|resp<onse]"
> <Reaso>n<Phrase[false|t>rue]/ReasonPhrase
/Copy
/AssignMessageExample 1
The following example sets <ReasonPhrase> to true . With the source and <AssignTo> element as specified, this causes <Copy> to copy the reason phrase from the named response message to the response object:
<AssignMessage name="AM-copy-reasonphra>se-<1" Copy source="serviceC>allou<tResponse&qu>ot; < ReasonPhr>ase<true/>Rea<sonPhras>e /Cop<y Assig>n<Toresponse/Ass>ignTo /AssignMessage
You can use <ReasonPhrase> only when the source and destination messages are of type Response.
<StatusCode> (child of <Copy> )
Determines whether the status code is copied from the source response to the destination response. This element has no effect on a request.
If "true", this policy copies the status code from the response message specified by the <Copy> element's source attribute to the response message specified by the <AssignTo> element.
| Значение по умолчанию | ЛОЖЬ |
| Необходимый? | Необязательный |
| Тип | Булевое значение |
| Parent Element | <Copy> |
| Child Elements | Никто |
The <StatusCode> element uses the following syntax:
Syntax
<AssignMessage
continueOnError="[false|true]"
enabled="[true|false]"
> na<me="policy_name"
Co>py so<urce=">;[request|re<sponse]&quo>t;
< S>t<atusCode[false>|true]/StatusCode
/Copy
/AssignMessageExample 1
The following example sets <StatusCode> to "true", which copies the status code from the default response object to a new, custom response object:
<AssignMessage name="copy-statusco>de-<1" Copy source=>"<;response&>quot<; Statu>sCo<detru>e/S<tatusCode /Copy AssignTo createNew="true" tr>ansport="ht<tp" >t<ype="resp>onse"MyCustomResponse/AssignTo /AssignMessage
You can use <StatusCode> only when the source and destination messages are of type Response.
A common use of <StatusCode> is to set the proxy response status code to a different value than that received from the target.
<Verb> (child of <Copy> )
Determines whether the HTTP verb is copied from the source request to the destination request. This element has no effect on a response.
If "true", copies the verb found in the <Copy> element's source attribute to the request specified in the <AssignTo> element.
| Значение по умолчанию | ЛОЖЬ |
| Необходимый? | Необязательный |
| Тип | Булевое значение |
| Parent Element | <Copy> |
| Child Elements | Никто |
The <Verb> element uses the following syntax:
Syntax
<AssignMessage
continueOnError="[false|true]"
enabled="[true|false]"
> na<me="policy_name"
Co>py so<urce>="[requ<est|r>esp<onse]>&<quot;
Verb>[false|true]/Verb
/Copy
/AssignMessageExample 1
The following example sets <Verb> to "true", which copies the verb from the default request to a new, custom request:
<AssignMessage name="copy-ve>rb-<1" Copy source>=&quo<t;re>ques<t&quo>t; < V>erb<true/Verb /Copy AssignTo createNew="true" t>ransport="<http">;< type="re>quest"MyCustomRequest/AssignTo /AssignMessage
You can use <Verb> only when the following criteria are met:
- Message type: Request
<Version> (child of <Copy> )
Determines whether the HTTP version is copied from the source request to the destination request. This element has no effect on a response.
If "true", copies the HTTP version found in the <Copy> element's source attribute to the object specified by the <AssignTo> element.
| Значение по умолчанию | ЛОЖЬ |
| Необходимый? | Необязательный |
| Тип | Булевое значение |
| Parent Element | <Copy> |
| Child Elements | Никто |
The <Version> element uses the following syntax:
Syntax
<AssignMessage
continueOnError="[false|true]"
enabled="[true|false]"
> na<me="policy_name"
Co>py so<urce=&q>uot;[request<|respons>e]&<quot;>
< Version[fa>lse|true]/Version
/Copy
/AssignMessageExample 1
The following example sets <Version> to "true" on the request, which copies the version from the default request object to a new, custom request object:
<AssignMessage name="copy-versi>on-<1" Copy source>=&quo<t;reque>st&q<uot; > Ve<rsion>tru<e/Version /Copy AssignTo createNew="true" t>ransport="<http">;< type="re>quest"MyCustomRequest/AssignTo /AssignMessage
You can use <Version> only when the following criteria are met:
- Message type: Request
<DisplayName>
Используйте в дополнение к атрибуту name , чтобы обозначить политику в редакторе прокси-сервера пользовательского интерфейса управления другим, более естественно звучащим именем.
Элемент <DisplayName> является общим для всех политик.
| Значение по умолчанию | н/д |
| Необходимый? | Необязательно. Если <DisplayName> опущен, будет использоваться значение атрибута name политики. |
| Тип | Нить |
| Родительский элемент | < PolicyElement > |
| Дочерние элементы | Никто |
Элемент <DisplayName> использует следующий синтаксис:
Синтаксис
<PolicyElement> <DisplayName>policy_display_name</DisplayName> ... </PolicyElement>
Пример
<PolicyElement> <DisplayName>My Validation Policy</DisplayName> </PolicyElement>
Элемент <DisplayName> не имеет атрибутов или дочерних элементов.
<IgnoreUnresolvedVariables>
Determines whether processing stops when an unresolved variable is encountered.
| Значение по умолчанию | ЛОЖЬ |
| Необходимый? | Необязательный |
| Тип | Булевое значение |
| Parent Element | <AssignMessage> |
| Child Elements | Никто |
Set to true to ignore unresolved variables and continue processing; otherwise false . The default value is false .
Setting <IgnoreUnresolvedVariables> to true is different from setting the <AssignMessage> 's continueOnError to true in that it is specific to setting and getting values of variables. If you set continueOnError to true , then Edge ignores all errors, not just errors encountered when using variables.
The <IgnoreUnresolvedVariables> element uses the following syntax:
Syntax
<AssignMessage
continueOnError="[false|true]"
enabled="[true|false]"
> na<me="policy_name">;
IgnoreUnre<solvedVariables[true|false>]<
/IgnoreUnre>solvedVariables
/AssignMessageExample 1
The following example sets <IgnoreUnresolvedVariables> to "true":
<AssignMessage name="AM-Set-Hea>der<s&q>uot; < Set > Head<ers Header name=>39;new-header'{possibly<-defin>ed-va<riable}H>ead<er > </Headers /Set IgnoreU>nresolv<edVariablestrue /IgnoreU>n<resolvedVariab>les /AssignMessage
Because <IgnoreUnresolvedVariables> is set to true , if the possibly-defined-variable variable is not defined, this policy will not throw a fault.
<Remove>
Removes headers, query parameters, form parameters, and/or the message payload from a message. The message can be a request or a response. You specify which message <Remove> acts on by using the <AssignTo> element.
| Значение по умолчанию | н/д |
| Необходимый? | Необязательный |
| Тип | Сложный тип |
| Parent Element | <AssignMessage> |
| Child Elements | <FormParams><Headers><Payload><QueryParams> |
A common use case for <Remove> is to delete a query parameter or header that contains sensitive information from the incoming request object, to avoid passing it to the backend server.
The <Remove> element uses the following syntax:
Syntax
<AssignMessage continueOnError="[false|true]" enabled="[true|false]" > na<me=&qu>ot;po<licy_name" Remove !-<- Can also >be an empt<y array (F>ormPara<ms/) --> FormParams > FormParam nam<e="fo>rmparam_name&qu<ot;formpara>m_val<ue/FormParam ... /Form<Params > !-- Can< also b>e an em<pty array (Headers/) --&g>t; Heade<rs > Header name=&<quot;hea>der_n<ame&quo>t;header_val<ue/Heade>r < ... /Headers Payload[<false|true]/>Payload < !-- Can a>lso be <an empty array (QueryParams/) --&>gt; QueryPar<ams Q>ueryParam name=<"queryp>ara<m_name&>q<uot;queryparam>_value/QueryParam ... /QueryParams /Remove /AssignMessage
Example 1
The following example removes the message's body from the response:
<AssignMessage name="AM-remo>ve-<1" D>isplayNa<meremove-1/D>isp<layNam>e R<emove > P<ayloadtr>ue/<Payload> </Remove > Assign<Torespons>e</AssignTo /Ass>ignMessage
In the response flow, this policy removes the body of the response, returning only HTTP headers to the client.
Example 2
The following example removes all form parameters and a query parameter from the request object:
<AssignMessage name="AM-remo>ve-<2">;
R<emove
!<-- Empty (F>ormParams/) removes all form par>amete<rs --
F>ormPa<rams/
Q>ueryPar<ams
QueryParam n>ame=&<quot;qp1&quo>t;/<
/Q>uer<yParams
> /Remo<ve
Assi>g<nTorequest/Ass>ignTo
/AssignMessageExample 3
The following example removes everything from a message object:
<AssignMessage name="AM-remo>ve-<3"> <Remove/ > Assig<nToreques>t</AssignTo /Ass>ignMessage
Typically you would do this only if you were going to use the <Set> element or the <Copy> element to set some replacement values in the message.
<FormParams> (child of <Remove> )
Removes the specified form parameters from the request. This element has no effect on a response.
| Значение по умолчанию | н/д |
| Необходимый? | Необязательный |
| Тип | Array of <FormParam> elements or an empty array |
| Parent Element | <Remove> |
| Child Elements | <FormParam> |
The <FormParams> element uses the following syntax:
Syntax
<AssignMessage continueOnError="[false|true]" enabled="[true|false]" > na<me=&qu>ot;po<licy_name" Remove !-<- Can also >be an empt<y array (F>ormPara<ms/) --> FormParams > FormParam nam<e="fo>rmparam_name&qu<ot;formpara>m_v<alue/Fo>r<mParam .>.. /FormParams /Remove /AssignMessage
Example 1
The following example removes three form parameters from the request:
<AssignMessage name="AM-remove-formpara>ms-<1">;
R<emove
>FormPar<ams
FormParam name=">;form_p<aram_1"/
FormParam >name=&q<uot;form_param_2"/
>FormP<aram name=&>quo<t;form_>par<am_3&quo>t;/
< /FormPar>a<ms
/Remove
> AssignTorequest/AssignTo
/AssignMessageExample 2
The following example removes all form parameters from the request:
<AssignMessage name="AM-remove-formpara>ms-<2">;
R<emove
F>orm<Params/>
</Remove
> Assig<nToreques>t</AssignTo
/Ass>ignMessageExample 3
If there are multiple form params with the same name, use the following syntax:
<AssignMessage name="AM-remove-formpara>ms-<3">;
R<emove
>FormPar<ams
FormParam >name=&q<uot;f1"/
>FormPar<am name="f2">/
< FormPara>m n<ame=&qu>ot;<f3.2&quo>t;/
< /FormPar>a<ms
/Remove
> AssignTorequest/AssignTo
/AssignMessageThis example removes "f1", "f2", and the second value of "f3". If "f3" has only one value, then it is not removed.
You can use <FormParams> only when the following criteria are met:
- Message type: Request
-
Content-Type: "application/x-www-form-urlencoded"
<Headers> (child of <Remove> )
Removes the specified HTTP headers from the request or response, which is specified by the <AssignTo> element.
| Значение по умолчанию | н/д |
| Необходимый? | Необязательный |
| Тип | Array of <Header> elements or an empty array |
| Parent Element | <Remove> |
| Child Elements | <Header> |
The <Headers> element uses the following syntax:
Синтаксис
<AssignMessage continueOnError="[false|true]" enabled="[true|false]" > na<me=&qu>ot;po<licy_name" Remove !-<- Can al>so be an e<mpty ar>ray (He<aders/) --> Header>s Head<er name>="header_n<ame">;he<ader_va>l<ue/Header > ... /Headers /Remove /AssignMessage
Example 1
The following example removes the user-agent header from the request:
<AssignMessage name="AM-remove-one-he>ade<r">;
R<emove
> Head<ers
Header name=&qu>ot;us<er-agent>&qu<ot;/
> /<Headers
> /Remo<ve
Assi>g<nTorequest/Ass>ignTo
/AssignMessageExample 2
The following example removes all headers from the request:
<AssignMessage name="AM-remove-all-hea>der<s">; R<emove > H<eaders/> </Remove > Assig<nToreques>t</AssignTo /Ass>ignMessage
Example 3
If there are multiple headers with the same name, use the following syntax:
<AssignMessage name="AM-remove-heade>rs-<3">;
R<emove
> Head<ers
Header >name=&q<uot;h1"/
> Head<er name="h2&qu>ot;/
< He>ade<r name=>&qu<ot;h3.2&>quot;/
< /Head>e<rs
/Remove
> AssignTorequest/AssignTo
/AssignMessageThis example removes "h1", "h2", and the second value of "h3" from the request. If "h3" has only one value, then it is not removed.
<Payload> (child of <Remove> )
Determines whether <Remove> deletes the payload in the request or response, which is specified by the <AssignTo> element. Set to "true" to clear the payload; otherwise "false". The default value is "false".
| Значение по умолчанию | ЛОЖЬ |
| Необходимый? | Необязательный |
| Тип | Булевое значение |
| Parent Element | <Remove> |
| Child Elements | Никто |
The <Payload> element uses the following syntax:
Синтаксис
<AssignMessage continueOnError="[false|true]" enabled="[true|false]" > na<me=&qu>ot;po<licy_na>me" <Remove > <Payload>[<false|true]/Pa>yload /Remove /AssignMessage
Example 1
The following example sets <Payload> to "true" so that the request payload is cleared:
<AssignMessage name="AM-remove-paylo>ad-<1">; R<emove > P<ayloadtr>ue/<Payload> </Remove > Assig<nToreques>t</AssignTo /Ass>ignMessage
<QueryParams> (child of <Remove> )
Removes the specified query parameters from the request. This element has no effect on a response.
| Значение по умолчанию | н/д |
| Необходимый? | Необязательный |
| Тип | Array of <QueryParam> elements or an empty array |
| Parent Element | <Remove> |
| Child Elements | <QueryParam> |
The <QueryParams> element uses the following syntax:
Syntax
<AssignMessage continueOnError="[false|true]" enabled="[true|false]" > na<me=&qu>ot;po<licy_name" Remove !-<- Can also b>e an empty< array (Que>ryParam<s/) --> QueryParams >QueryParam name=<"query>param_name"<;queryparam_>val<ue/Quer>y<Param ..>. /QueryParams /Remove /AssignMessage
Example 1
The following example removes a single query parameter from the request:
<AssignMessage name="AM-remove-querypara>ms-<1">;
Rem<ove
Q>ueryParam<s
QueryParam n>ame=&qu<ot;qp1">/
< /Q>uer<yParams
> /Remo<ve
Assi>g<nTorequest/Ass>ignTo
/AssignMessageExample 2
The following example removes all query parameters from the request:
<AssignMessage name="AM-remove-querypara>ms-<2">;
Rem<ove
Qu>ery<Params/>
</Remove
> Assig<nToreques>t</AssignTo
/Ass>ignMessageExample 3
If there are multiple query params with the same name, use the following syntax:
<AssignMessage name="AM-remove-querypara>ms-<3">;
Rem<ove
Q>ueryParam<s
QueryParam n>ame="<;qp1"/
Qu>eryParam <name="qp2"/
> Q<ueryParam na>me=<"q>p3.<2"/>
</QueryPar>a<ms
/Remove
> AssignTorequest/AssignTo
/AssignMessageThis example removes "qp1", "qp2", and the second value of "qp3" from the request. If "qp3" has only one value, then it is not removed.
Example 4
The following example removes the apikey query parameter from the request:
<AssignMessage name="AM-remove-query-p>ara<m">;
R<emove
Q>ueryPar<ams
QueryParam name>=&quo<t;apikey&quo>t;/<
/Q>uer<yParams
> /Remo<ve
Assi>g<nTorequest/Ass>ignTo
/AssignMessage You can use <QueryParams> only when the following criteria are met:
- HTTP verb: GET
- Message type: Request
<Set>
Sets information in the request or response message, which is specified by the <AssignTo> element. <Set> overwrites headers or query or form parameters that already exist in the original message. Headers and query and form parameters in an HTTP message may hold multiple values. To add additional values for a header or parameter, use the <Add> element instead.
| Значение по умолчанию | н/д |
| Необходимый? | Необязательный |
| Тип | Сложный тип |
| Parent Element | <AssignMessage> |
| Child Elements | <FormParams><Headers><Payload><Path><QueryParams><ReasonPhrase><StatusCode><Verb><Version> |
The <Set> element uses the following syntax:
Синтаксис
<AssignMessage continueOnError="[false|true]" enabled="[true|false]" > na<me=>"<;policy_na>me"<; Set FormParams F>ormParam name=&<quot;formp>aram_name"<formparam_v>alue/<FormPar>am < ... /FormParams > Headers < Head>er name="h<eader_na>me&qu<ot;h>eade<r_val>ue/He<ader ... /Headers Pathpath/Path Payload contentType="content_type&q>uot; variab<lePrefix>=&quo<t;prefix&qu>ot; < variableSuffix="suffix&>quot;new_payload</Payload > QueryParams < QueryPa>ram n<ame="qu>eryparam_name"queryparam_<value/QueryPa>ram < ... > /QueryParams ReasonPhra<sereason_fo>r_err<or o>r {variable}/ReasonPhrase StatusCo<deHTT>P_sta<tus_cod>e or {variable}/Stat<usCod>e < V>e<rb[GET|POST|PU>T|PATCH|DELETE|{variable}]/Verb Version[1.0|1.1|{variable}]/Verb /Set /AssignMessage
Example 1
The following example sets a specific header. When this policy is attached in the Request flow, it will allow the upstream system to receive an additional header that was not included in the original inbound request.
<AssignMessage name="AM-Set-He>ade<r&q>uot;
< Set
> Header<s
Header name="authentic>ated-developer"{verifyapikey<.VAK-1.>devel<oper.id}>/He<ader>
< /Heade>rs
/S<et
Assi>g<nTorequest/Ass>ignTo
/AssignMessageExample 2
The following example overwrites the payload for a response, as well as the Content-Type header.
<AssignMessage name="AM-Overwrite-Pay>loa<d&q>uot; < Set Payload contentType="ap>plication/json&qu<ot;{ &qu>ot;<stat>us&<quot; : >42 }/Pay<load /S>e<t AssignTore>sponse/AssignTo /AssignMessage
<FormParams> (child of <Set> )
Overwrites existing form parameters on a request and replaces them with the new values that you specify with this element. This element has no effect on a response.
| Значение по умолчанию | н/д |
| Необходимый? | Необязательный |
| Тип | Array of <FormParam> elements |
| Parent Element | <Set> |
| Child Elements | <FormParam> |
The <FormParams> element uses the following syntax:
Syntax
<AssignMessage
continueOnError="[false|true]"
enabled="[true|false]"
> na<me=>"<;policy_na>me"<;
Set
FormParams
F>ormParam name=&<quot;formp>aram_name"<formparam_v>alu<e/Fo>r<mParam
.>..
/FormParams
/Set
/AssignMessageExample 1
The following example sets a form parameter called "myparam" to the value of the request.header.myparam variable in a new, custom request:
<AssignMessage name="AM-set-formpara>ms-<1&q>uot; < Set >FormPar<ams FormParam name>="myparam"{req<uest.heade>r.myp<aram}/FormP>ara<m > /<FormParams /Set AssignTo createNew="true" t>ransport="<http">;< type="re>quest"MyCustomRequest/AssignTo /AssignMessage
You can use <FormParams> only when the following criteria are met:
- HTTP verb: POST
- Message type: Request
If you define empty form parameters in your policy ( <Add><FormParams/></Add> ), the policy does not add any form parameters. This is the same as omitting the <FormParams> .
<Set> changes the Content-Type of the message to "application/x-www-form-urlencoded" before sending it to the target endpoint.
<Headers> (child of <Set> )
Overwrites existing HTTP headers in the request or response, which is specified by the <AssignTo> element.
| Значение по умолчанию | н/д |
| Необходимый? | Необязательный |
| Тип | Array of <Header> elements |
| Parent Element | <Set> |
| Child Elements | <Header> |
The <Headers> element uses the following syntax:
Syntax
<AssignMessage
continueOnError="[false|true]"
enabled="[true|false]"
> na<me=>"<;policy>_name&q<uot;
Set
Headers
> Header <name=&q>uot;header_name<"he>ade<r_va>l<ue/Header
> ...
/Headers
/Set
/AssignMessageExample 1
The following example sets the x-ratelimit-remaining header to the value of the ratelimit.Quota-1.available.count variable:
<AssignMessage name="AM-Set-RateLimit-He>ade<r&q>uot;
< Set
> Head<ers
Header name="X-RateL>imit-Remaining"{ratelimit.Quot<a-1.ava>ilabl<e.count}>/He<ader>
< /Heade>rs
/Se<t
Assig>n<Toresponse/Ass>ignTo
/AssignMessage If you define empty headers in your policy ( <Set><Headers/></Set> ), the policy does not set any headers. This will have the same effect as omitting <Headers> .
<Path> (child of <Set> )
<Payload> (child of <Set> )
Defines the message body for a request or response, which is specified by the <AssignTo> element. The payload can be any valid content type, such as plain text, JSON, or XML.
| Значение по умолчанию | empty string |
| Необходимый? | Необязательный |
| Тип | Нить |
| Parent Element | <Set> |
| Child Elements | Никто |
The <Payload> element uses the following syntax:
Syntax
<AssignMessage continueOnError="[false|true]" enabled="[true|false]" > na<me=>"<;policy_name" Set Payload contentType="content_type" variablePrefix=>"prefi<x"<>/span> < > <variableSuffix>="suffix"new_payload/Payload /Set /AssignMessage
Example 1
The following example sets a plain text payload:
<AssignMessage name="set-paylo>ad-<1&q>uot; < Set Payload contentType=&q>uo<t;text/p>lai<n&qu>o<t;42/Payload > /Set /AssignMessage
Example 2
The following example sets a JSON payload:
<AssignMessage name="set-paylo>ad-<2&q>uot; < Set Payload contentType="ap>plication/json" {"name&q<uot;:&qu>ot;<foo&>q<uot;, "ty>pe":"bar"} /Payload /Set /AssignMessage
Example 3
The following example inserts variable values into the payload by wrapping variable names in curly braces:
<AssignMessage name="set-paylo>ad-<3&q>uot; < Set Payload contentType="ap>plication/json" {"name":"f<oo">, &<quot>;<type":&qu>ot;{variable_name}"} /Payload /Set /AssignMessage
In previous versions of Apigee, you could not use curly braces to denote variable references within JSON payloads. In those releases, you needed to use the variablePrefix and variableSuffix attributes to specify delimiter characters, and use those to wrap variable names, like so:
<AssignMessage name="set-payloa>d-3<b&q>uot; < Set Payload contentType="application/json" variablePrefix=&q>uot;@" variableSuffix="#" {&quo<t;name&q>uot<;:&q>u<ot;foo", >"type":"@variable_name#"} /Payload /Set /AssignMessage
This older syntax still works.
Example 4
The content of <Payload> is treated as a message template. This means that the AssignMessage policy replaces variables wrapped in curly braces with the value of the referenced variables at runtime.
The following example uses the curly braces syntax to set part of the payload to a variable value:
<AssignMessage name="set-paylo>ad-<4&q>uot; < Set Payload contentType=>"t<ext/>xml"< > r<oot> <e1>sunday</e1> <e2>funday</e2> < e3{>var1}</e3 > /<root> < /Payload > /Set /AssignMessage
The following table describes the attributes of <Payload> :
| Атрибут | Описание | Присутствие | Тип |
|---|---|---|---|
contentType | If specified, the value of | Необязательный | Нить |
variablePrefix | Optionally specifies the leading delimiter on a flow variable. Defaults to "{". For more information, see Flow variables reference . | Необязательный | Чар |
variableSuffix | Optionally specifies the trailing delimiter on a flow variable. Defaults to "}". For more information, see Flow variables reference . | Необязательный | Чар |
<QueryParams> (child of <Set> )
Overwrites existing query parameters in the request with new values. This element has no effect on a response.
| Значение по умолчанию | н/д |
| Необходимый? | Необязательный |
| Тип | Array of <QueryParam> elements |
| Parent Element | <Set> |
| Child Elements | <QueryParam> |
The <QueryParams> element uses the following syntax:
Syntax
<AssignMessage
continueOnError="[false|true]"
enabled="[true|false]"
> na<me=>"<;policy_nam>e"<
Set
QueryParams
Que>ryParam name=&qu<ot;querypar>am_name"qu<eryparam_val>ue/<Quer>y<Param
..>.
/QueryParams
/Set
/AssignMessageExample 1
The following example sets the "address" query parameter to the value of the request.header.address variable:
<AssignMessage name="AM-set-querypara>ms<-1&>quot;< Set Q>ueryPar<ams QueryParam name>="address"{req<uest.header>.addr<ess}/QueryPa>ram< > </QueryParams > /Set /AssignMessage
You can use <QueryParams> only when the following criteria are met:
- HTTP verb: GET
- Message type: Request
If you define empty query parameters in your policy ( <Set><QueryParams/></Set> ), the policy does not set any query parameters. This is the same as omitting <QueryParams> .
<ReasonPhrase> (child of <Set> )
Sets the reason phrase on the response. This is normally done for debugging in combination with <StatusCode> . This element has no effect on a request.
| Значение по умолчанию | н/д |
| Необходимый? | Необязательный |
| Тип | Нить |
| Parent Element | <Set> |
| Child Elements | Никто |
The <ReasonPhrase> element uses the following syntax:
Syntax
<AssignMessage continueOnError="[false|true]" enabled="[true|false]" > na<me=>"<;policy_name>" Set ReasonPhrase<reason_for_er>ror< or >{<variable}/Reas>onPhrase /Set /AssignMessage
Example 1
The following example defines a simple reason phrase:
<AssignMessage name="set-reasonphra>se-<1&q>uot; < Set Re>asonPhraseBa<d medicine/Re>aso<nPhr>ase< /Set AssignTo createNew="true" transport=&qu>o<t;http" t>ype="response"/ /AssignMessage
Example 2
The content of <ReasonPhrase> is treated as a message template. This means a variable name wrapped in curly braces will be replaced at runtime with the value of the referenced variable, as the following example shows:
<AssignMessage name="AM-set-reasonphra>se-<2&q>uot;
< Set
Re>asonPhrase{calloutresponse.reas<on.phrase}/Re>aso<nPhr>ase<
/Set
> Assign<Torespons>e</AssignTo
/Ass>ignMessage You can use <ReasonPhrase> only when the following criteria are met:
- Message type: Response
<StatusCode> (child of <Set> )
Sets the status code on the response. This element has no effect on a request.
| Значение по умолчанию | '200' (when <AssignTo> 's createNew attribute is set to 'true') |
| Необходимый? | Необязательный |
| Тип | String or variable |
| Parent Element | <Set> |
| Child Elements | Никто |
The <StatusCode> element uses the following syntax:
Syntax
<AssignMessage continueOnError="[false|true]" enabled="[true|false]" > na<me=>"<;policy_na>me" Set StatusCode<HTTP_status>_co<de o>r< {variable}/St>atusCode /Set /AssignMessage
Пример 1
The following example sets a simple status code:
<AssignMessage name="AM-set-statuscode>-40<4&q>uot;
< Set
>Sta<tusCode404/>Sta<tusC>ode<
/Set
> Assign<Torespons>e</AssignTo
/Ass>ignMessageПример 2
The content of <StatusCode> is treated as a message template. This means a variable name wrapped in curly braces will be replaced at runtime with the value of the referenced variable, as the following example shows:
<AssignMessage name="set-statusco>de-<2&q>uot;
< Set
>StatusCode{calloutresponse.st<atus.code}/>Sta<tusC>ode<
/Set
> Assign<Torespons>e</AssignTo
/Ass>ignMessage You can use <StatusCode> only when the following criteria are met:
- Message type: Response
<Verb> (child of <Set> )
Sets the HTTP verb on the request. This element has no effect on a response.
| Значение по умолчанию | н/д |
| Необходимый? | Необязательный |
| Тип | String or variable |
| Parent Element | <Set> |
| Child Elements | Никто |
The <Verb> element uses the following syntax:
Синтаксис
<AssignMessage continueOnError="[false|true]" enabled="[true|false]" > na<me=>"<;pol>icy_name" Set Verb[GET|POS<T|PUT>|PA<TCH|>D<ELETE|{variabl>e}]/Verb /Set /AssignMessage
Example 1
The following example sets a simple verb on the request:
<AssignMessage name="AM-set-ve>rb-<1&q>uot; < Se>t < Ver>bPO<ST/V>erb< /Set > Assig<nToreques>t</AssignTo /Ass>ignMessage
Example 2
The content of <Verb> is treated as a message template. This means a variable name wrapped in curly braces will be replaced at runtime with the value of the referenced variable.
The following example uses a variable to populate a verb:
<AssignMessage name="AM-set-verb-to-dynamic-v>alu<e&q>uot; < Se>t Verb{my<_vari>abl<e}/V>erb< /Set > Assig<nToreques>t</AssignTo /Ass>ignMessage
You can use <Verb> only when the following criteria are met:
- Message type: Request
<Version> (child of <Set> )
Sets the HTTP version on a request. This element has no effect on a response.
| Значение по умолчанию | н/д |
| Необходимый? | Необязательный |
| Тип | String or variable |
| Parent Element | <Set> |
| Child Elements | Никто |
The <Version> element uses the following syntax:
Syntax
<AssignMessage continueOnError="[false|true]" enabled="[true|false]" > na<me=>"<;policy>_name" Set < Ve>rsi<on[1>.<0|1.1|{variabl>e}]/Verb /Set /AssignMessage
Example 1
The following example sets the version number to "1.1":
<AssignMessage name="AM-set-versi>on-<1&q>uot; < Set > <Version1>.1/<Vers>io<n /Set /Ass>ignMessage
Пример 2
The following uses a variable in curly braces to set the version number:
<AssignMessage name="AM-set-versi>on-<2&q>uot;
< Set
> Version{m<y_versio>n}/<Vers>ion<
/Set
> Assig<nToreques>t</AssignTo
/Ass>ignMessage The content of <Version> is treated as a message template. This means a variable name wrapped in curly braces will be replaced at runtime with the value of the referenced variable.
You can use <Version> only when the following criteria are met:
- Message type: Request
The following example creates a custom request object with Assign Message:
<AssignMessage name="AssignMessa>ge-<3" AssignTo createNew="true&>quot; type=&quo<t;request>&qu<ot;M>yCust<omReque>st/Ass<ignTo Copy Headers > <Header n>ame<=&quo>t;u<ser>-agen<t"/ > /Head<ers /Copy Set Que>ryParams QueryParam< name=">;addr<ess"{re>quest<.que>ryp<aram.>add<y}/Q>uer<yParam /QueryParams > VerbG<ET/Verb /Set IgnoreUnr>e<solvedVariable>sfalse /IgnoreUnresolvedVariables /AssignMessage
This example:
- Creates a new request message object called "MyCustomRequest".
- On MyCustomRequest, this policy:
- Copies the value of the
user-agentHTTP header from the incoming request to the new message. Because<Copy>uses an absolute reference to theuser-agentflow variable, there is no need to specify thesourceattribute to<Copy>. - Sets the
addressquery parameter on the custom message to the value of the incoming request'saddyquery parameter. - Sets the HTTP verb to
GET.
- Copies the value of the
- Sets
<IgnoreUnresolvedVariables>to "false". When<IgnoreUnresolvedVariables>is "false", if one of the variables the policy tries to add does not exist, Edge will stop processing in the API flow.
Example 2
Here's another example demonstrating how to create a custom request object with Assign Message:
<AssignMessage name="AssignMessa>ge-<2" AssignTo createNew="true&>quot; type=&quo<t;request>&qu<ot;>partn<er.r>eque<st/As>signT<o Set VerbPOST/Verb >Payload< conten><tType=&qu>ot;<text/xml&q><uot; > re<questope>rat<ion1>0<5/operation/re>quest /Payload /Set /AssignMessage
This example creates a new custom request called "partner.request". It then sets the <Verb> and <Payload> on the new request.