### Setup Example Solution
Source: https://github.com/azure/azure-api-management-policy-toolkit/blob/main/docs/DevEnvironmentSetup.md
Executes a script to set up the example solution. Alternatively, manual build steps can be followed.
```shell
setup-example.cmd
```
--------------------------------
### Install Policy Toolkit Authoring Templates
Source: https://github.com/azure/azure-api-management-policy-toolkit/blob/main/src/Templates/README.md
Use this command to install the necessary NuGet package for authoring policies with the toolkit.
```dotnetcli
dotnet new install Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring
```
--------------------------------
### Build Project
Source: https://github.com/azure/azure-api-management-policy-toolkit/blob/main/docs/DevEnvironmentSetup.md
Builds the entire project. This command is used both for the main toolkit and for example projects.
```shell
dotnet build
```
--------------------------------
### Create New Solution and Class Library
Source: https://github.com/azure/azure-api-management-policy-toolkit/blob/main/docs/QuickStart.md
Initial project setup commands to create a solution and a class library for policy documents.
```shell
dotnet new sln --output PolicySolution
cd PolicySolution
```
```shell
dotnet new classlib --output Contoso.Apis.Policies
dotnet sln add ./Contoso.Apis.Policies
```
--------------------------------
### Restore Compiler Tool
Source: https://github.com/azure/azure-api-management-policy-toolkit/blob/main/docs/DevEnvironmentSetup.md
Restores the necessary compiler tool for the example project.
```shell
dotnet tool restore
```
--------------------------------
### Install Policy Toolkit Compiler CLI
Source: https://github.com/azure/azure-api-management-policy-toolkit/blob/main/src/Compiling/README.md
Installs the Microsoft Azure Api Management Policy Toolkit compiler CLI tool globally using NuGet.
```shell
dotnet tool install Azure.ApiManagement.PolicyToolkit.Compiling
```
--------------------------------
### APIOps Repository Structure Example
Source: https://github.com/azure/azure-api-management-policy-toolkit/blob/main/docs/IntegratePolicySolutionWithApiOps.md
Illustrates a typical folder structure for an APIOps repository, including policy files within artifacts.
```tree
.
├── artifacts
│ ├── policy.xml
│ ├── apis
│ │ └── echo-api
│ │ ├── policy.xml
│ │ └── operations
│ │ ├── get
│ │ │ └── policy.xml
│ │ └── post
│ │ └── policy.xml
│ └── products
│ └── Unlimited
│ └── policy.xml
└── configuration.dev.yaml
```
--------------------------------
### Add Microsoft Azure Api Management Policy Toolkit Package
Source: https://github.com/azure/azure-api-management-policy-toolkit/blob/main/src/Authoring/README.md
Install the policy authoring library for .NET using NuGet.
```dotnetcli
dotnet add package Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring
```
--------------------------------
### Install Policy Compiler Tool
Source: https://github.com/azure/azure-api-management-policy-toolkit/blob/main/docs/QuickStart.md
Installs the Azure API Management policy compiler as a global dotnet tool. This tool is required for compiling C# policy definitions into Razor format.
```shell
cd .. # Go to solution folder if not already there
dotnet tool install Azure.ApiManagement.PolicyToolkit.Compiling
```
--------------------------------
### Compile Policies to Flat Structure
Source: https://github.com/azure/azure-api-management-policy-toolkit/blob/main/docs/SolutionStructureRecommendation.md
Use this command to compile policy files from the src directory and output them into a flat target directory. Ensure the policy compiler is installed.
```shell
dotnet azure-apim-policy-compiler --s .\src\ --o .\target\
```
--------------------------------
### Write Unit Test for Policy Expression
Source: https://github.com/azure/azure-api-management-policy-toolkit/blob/main/src/Testing/README.md
Example of writing a unit test using the testing library to verify a policy expression. Includes necessary usings and a test method.
```csharp
using Contoso.Apis.Policies;
using Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Expressions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Contoso.Apis.Policies.Tests;
[TestClass]
public class ApiOperationPolicyTest
{
[TestMethod]
public void TestHelloFromExpression()
{
var context = new MockExpressionContext();
Assert.AreEqual("World", ApiOperationPolicy.HelloFromExpression(context));
}
}
```
--------------------------------
### Install Policy Toolkit Testing Package
Source: https://github.com/azure/azure-api-management-policy-toolkit/blob/main/src/Testing/README.md
Use this command to add the Microsoft Azure Api Management Policy Toolkit test library to your project via NuGet.
```dotnetcli
dotnet add package Microsoft.Azure.ApiManagement.PolicyToolkit.Testing
```
--------------------------------
### Write a Custom API Operation Policy in C#
Source: https://github.com/azure/azure-api-management-policy-toolkit/blob/main/src/Authoring/README.md
Example of creating an inbound policy that sets a custom header using an expression. Ensure the necessary namespaces are included.
```csharp
using Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring;
using Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring.Expressions;
namespace Contoso.Apis.Policies;
[Document]
public class ApiOperationPolicy : IDocument
{
public void Inbound(IInboundContext context)
{
context.Base();
context.SetHeader("X-Hello", HelloFromExpression(context.ExpressionContext));
}
string HelloFromExpression(IExpressionContext context) => "World";
}
```
--------------------------------
### Example of Invoking a Method in Field Initialization
Source: https://github.com/azure/azure-api-management-policy-toolkit/blob/main/docs/QuickStart.md
Illustrates how to invoke a custom method within the field initialization of a policy configuration object. This pattern is useful for more complex policies requiring dynamic values.
```csharp
context.SomePolicy(new Config()
{
Field = Method(context.ExpressionContext)
});
```
--------------------------------
### Inspect Generated Policy XML
Source: https://github.com/azure/azure-api-management-policy-toolkit/blob/main/src/Compiling/README.md
Example of a generated Azure API Management XML policy document using Razor syntax for dynamic values.
```cshtml
@("World")
```
--------------------------------
### Set up Test Project and References
Source: https://github.com/azure/azure-api-management-policy-toolkit/blob/main/docs/QuickStart.md
Use these commands to create a new MSTest project, add it to the solution, reference the policy project, and create a test class.
```shell
dotnet new mstest --output Contoso.Apis.Policies.Tests
dotnet sln add ./Contoso.Apis.Policies.Tests
cd Contoso.Apis.Policies.Tests
dotnet add package Microsoft.Azure.ApiManagement.PolicyToolkit.Testing
dotnet add reference ..\Contoso.Apis.Policies
dotnet new class -n ApiOperationPolicyTest
```
--------------------------------
### Pack Project
Source: https://github.com/azure/azure-api-management-policy-toolkit/blob/main/docs/DevEnvironmentSetup.md
Creates NuGet packages for the project. The output is placed in the 'output' directory.
```shell
dotnet pack
```
--------------------------------
### Create New Policy Toolkit Class File
Source: https://github.com/azure/azure-api-management-policy-toolkit/blob/main/src/Templates/README.md
Use this command to generate a new C# class file for a policy within the toolkit.
```dotnetcli
dotnet new policytoolkitclass
```
--------------------------------
### Create New Policy Toolkit Solution Project
Source: https://github.com/azure/azure-api-management-policy-toolkit/blob/main/src/Templates/README.md
Run this command to generate a new C# project structure for your API Management policy toolkit solution.
```dotnetcli
dotnet new policytoolkitsolution
```
--------------------------------
### Run Tests
Source: https://github.com/azure/azure-api-management-policy-toolkit/blob/main/docs/DevEnvironmentSetup.md
Executes all defined unit tests for the project.
```shell
dotnet test
```
--------------------------------
### Restore Dependencies
Source: https://github.com/azure/azure-api-management-policy-toolkit/blob/main/docs/DevEnvironmentSetup.md
Run this command after cloning the repository to restore project dependencies.
```shell
dotnet restore
```
--------------------------------
### Compile Policy Documents
Source: https://github.com/azure/azure-api-management-policy-toolkit/blob/main/docs/IntegratePolicySolution.md
Use this command to compile policy documents using the policy toolkit. Specify the source directory for C# files and the output directory for the compiled XML policy files.
```shell
dotnet azure-apim-policy-compiler --s .\src\ --o .\infrastructure\
```
--------------------------------
### Add Policy Toolkit Authoring Package
Source: https://github.com/azure/azure-api-management-policy-toolkit/blob/main/docs/QuickStart.md
Command to add the policy authoring toolkit package to the class library project.
```shell
cd ./Contoso.Apis.Policies
dotnet add package Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring
```
--------------------------------
### Implement Custom Policy Compiler
Source: https://github.com/azure/azure-api-management-policy-toolkit/blob/main/docs/AddPolicyGuide.md
Implement the IMethodPolicyHandler interface to translate C# method calls into XML policy elements. Use TryExtractingConfigParameter for configuration and AddAttribute for XML attributes. Report diagnostics for missing parameters.
```csharp
namespace Microsoft.Azure.ApiManagement.PolicyToolkit.Compiling.Policy;
public class YourPolicyCompiler : IMethodPolicyHandler
{
public string MethodName => nameof(IInboundContext.YourPolicy);
public void Handle(IDocumentCompilationContext context, InvocationExpressionSyntax node)
{
if (!node.TryExtractingConfigParameter(context, "your-policy", out var values))
{
return;
}
var element = new XElement("your-policy");
if (!element.AddAttribute(values, nameof(YourPolicyConfig.Property), "propery"))
{
context.Report(Diagnostic.Create(
CompilationErrors.RequiredParameterNotDefined,
node.GetLocation(),
"your-policy",
nameof(YourPolicyConfig.Property)
));
return;
}
element.AddAttribute(values, nameof(YourPolicyConfig.OptionalProperty), "optional-property");
context.AddPolicy(element);
}
}
```
--------------------------------
### Deploy Policy with Azure CLI
Source: https://github.com/azure/azure-api-management-policy-toolkit/blob/main/docs/IntegratePolicySolution.md
Execute this Azure CLI command to deploy the Bicep template and associated policy documents to your Azure API Management instance. Ensure you replace placeholders with your actual resource group and service name.
```shell
cd .\infrastructure\
az deployment group create \
--resource-group <> \
--template-file .\deployment.bicep \
--parameters servicename=<> \
--name deploy-1
```
--------------------------------
### Compile Policy Toolkit Source to APIM Policy Document
Source: https://github.com/azure/azure-api-management-policy-toolkit/blob/main/docs/QuickStart.md
Command to compile C# policy definitions into an Azure API Management policy XML document using the dotnet CLI. Use the --s flag for the source directory and --o for the output directory.
```shell
dotnet azure-apim-policy-compiler --s .\source\ --o . --format true
```
--------------------------------
### Write Test for IsCompanyIP Expression
Source: https://github.com/azure/azure-api-management-policy-toolkit/blob/main/docs/QuickStart.md
Implement a unit test using MSTest to verify the IsCompanyIP policy expression. Mock the request context with different IP addresses to assert expected boolean outcomes.
```csharp
using Contoso.Apis.Policies;
using Microsoft.Azure.ApiManagement.PolicyToolkit.Testing.Expressions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Newtonsoft.Json.Linq;
namespace Contoso.Apis.Policies.Tests;
[TestClass]
public class ApiOperationPolicyTest
{
[TestMethod]
public void FilterSecrets()
{
var context = new MockExpressionContext();
context.Request.IpAddress = "10.0.0.12";
Assert.IsTrue(ApiOperationPolicy.IsCompanyIP(context));
context.Request.IpAddress = "11.0.0.1";
Assert.IsFalse(ApiOperationPolicy.IsCompanyIP(context));
}
}
```
--------------------------------
### Adding Policy Project to APIOps Repository
Source: https://github.com/azure/azure-api-management-policy-toolkit/blob/main/docs/IntegratePolicySolutionWithApiOps.md
Shows how to integrate a policy project as a subfolder within an APIOps repository, including .NET tools configuration.
```tree
.
├── artifacts
│ ├── policy.xml
│ ├── apis
│ │ └── echo-api
│ │ ├── policy.xml
│ │ └── operations
│ │ ├── get
│ │ │ └── policy.xml
│ │ └── post
│ │ └── policy.xml
│ └── products
│ └── Unlimited
│ └── policy.xml
├── configuration.dev.yaml
├── .config
│ └── dotnet-tools.json
└── policies
├── policies.sln
├── src
│ ├── src.csproj
│ ├── apis
│ │ └── echo-api
│ │ ├── ApiEchoApiPolicy.cs
│ │ └── operations
│ │ ├── get
│ │ │ └── ApiEchoApiGetPolicy.cs
│ │ └── post
│ │ └── ApiEchoApiPostPolicy.cs
│ └── products
│ └── Unlimited
│ └── ProductUnlimitedPolicy.cs
└── test
├── test.csproj
...
```
--------------------------------
### GitHub Actions Pipeline for Policy Deployment
Source: https://github.com/azure/azure-api-management-policy-toolkit/blob/main/docs/IntegratePolicySolution.md
This GitHub Actions workflow automates the checkout, build, test, and deployment of policy documents for Azure API Management. It requires Azure credentials to be configured as a secret.
```yaml
on:
workflow_dispatch:
inputs:
resourceGroup:
description: 'The resource group of the Azure API Management instance'
required: true
apimServiceName:
description: 'The name of the Azure API Management instance'
required: true
name: DeployPolicyDocuments
jobs:
build-and-deploy:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v3
- name: Setup .NET
uses: actions/setup-dotnet@v3
with:
dotnet-version: 8.0.x
- name: Restore dependencies
run: dotnet restore
- name: Build with dotnet
run: dotnet build --no-restore
- name: Test with dotnet
run: dotnet test --no-build --logger trx --results-directory "TestResults"
- name: Upload dotnet test results
if: "${{ always() }}"
uses: actions/upload-artifact@v4
with:
name: dotnet-test-results
path: TestResults
- name: Restore policy document compiler
run: dotnet tool restore
- name: Compile policy documents
run: dotnet azure-apim-policy-compiler --s .\src\ --o .\infrastructure\
- name: Azure Login
uses: azure/login@v2
with:
creds: "${{ secrets.AZURE_CREDENTIALS }}"
- name: Deploy policy documents
uses: azure/cli@v2
env:
AZURE_RESOURCE_GROUP: "${{ inputs.resourceGroup }}"
AZURE_API_MANAGEMENT_SERVICE_NAME: "${{ inputs.apimServiceName }}"
RUN_NUMBER: "${{ github.run_number }}"
with:
azcliversion: latest
inlineScript: |
cd .\infrastructure\
az deployment group create \
--resource-group $AZURE_RESOURCE_GROUP \
--template-file .\deployment.bicep \
--parameters servicename=$AZURE_API_MANAGEMENT_SERVICE_NAME \
--name deploy-$RUN_NUMBER
```
--------------------------------
### Document Product Policy
Source: https://github.com/azure/azure-api-management-policy-toolkit/blob/main/docs/SolutionStructureRecommendation.md
Use the Document attribute to specify the output path for a product policy. This facilitates the organization of product-specific policies into designated directories.
```csharp
[Document("products/Starter/policy.xml")]
public class ProductStarterPolicy : IDocument
```
--------------------------------
### Add Policy Method to Context Interface
Source: https://github.com/azure/azure-api-management-policy-toolkit/blob/main/docs/AddPolicyGuide.md
Add a method signature to the relevant section context interface (e.g., IInboundContext) to make the policy available. Ensure the method includes XML documentation detailing its purpose and parameters.
```csharp
///
/// Description of your policy.
///
/// Configuration for the YourPolicy policy.
///
///
void YourPolicy(YourPolicyConfig config);
```
--------------------------------
### Cross-Domain Policy
Source: https://github.com/azure/azure-api-management-policy-toolkit/blob/main/docs/AvailablePolicies.md
Configures cross-domain access policy for Silverlight and Flash clients. Allows access from specified domains.
```csharp
c.CrossDomain("");
```
--------------------------------
### Inline Policy Workaround
Source: https://github.com/azure/azure-api-management-policy-toolkit/blob/main/docs/AvailablePolicies.md
Allows inclusion of policies not yet implemented in the toolkit. This serves as a workaround for missing native policies.
```csharp
c.InlinePolicy("");
```
--------------------------------
### Compile Policy Document
Source: https://github.com/azure/azure-api-management-policy-toolkit/blob/main/docs/QuickStart.md
Executes the policy compiler to generate a Razor policy document from C# source files. Specify the source folder, output folder, and formatting options.
```shell
dotnet azure-apim-policy-compiler --s .\Contoso.Apis.Policies --o . --format true
```
--------------------------------
### Bicep Deployment Template
Source: https://github.com/azure/azure-api-management-policy-toolkit/blob/main/docs/IntegratePolicySolution.md
This Bicep template defines the deployment of an API policy to an Azure API Management service. It references an existing API and loads the policy content from a local XML file.
```bicep
param servicename string
resource service 'Microsoft.ApiManagement/service@2023-03-01-preview' existing = {
name: servicename
scope: resourceGroup()
}
resource echoApi 'Microsoft.ApiManagement/service/apis@2023-03-01-preview' existing = {
parent: service
name: 'echo-api'
}
resource echoApiPolicy 'Microsoft.ApiManagement/service/apis/policies@2023-03-01-preview' = {
parent: echoApi
name: 'policy'
properties: {
format: 'rawxml'
value: loadTextContent('./apis/${echoApi.name}/ApiEchoApiPolicy.xml', 'utf-8')
}
}
```
--------------------------------
### Compile Policies
Source: https://github.com/azure/azure-api-management-policy-toolkit/blob/main/docs/DevEnvironmentSetup.md
Compiles policies using the Azure API Management policy compiler. Specify source and target directories.
```shell
dotnet azure-apim-policy-compiler --s .\source\ --o .\target\ --format true
```
--------------------------------
### Compile Policies for APIOps
Source: https://github.com/azure/azure-api-management-policy-toolkit/blob/main/docs/IntegratePolicySolutionWithApiOps.md
Command to run the Azure API Management policy compiler, targeting the policy source directory and outputting to the APIOps artifacts folder.
```shell
dotnet azure-apim-policy-compiler --s .\policies\src\ --o .\artifacts\
```
--------------------------------
### Define Policy Configuration Record
Source: https://github.com/azure/azure-api-management-policy-toolkit/blob/main/docs/AddPolicyGuide.md
Define a public record for your policy's configuration. Use 'required' for mandatory parameters and 'nullable' for optional ones. Apply '[ExpressionAllowed]' attribute for properties that support policy expressions. Include XML documentation for clarity.
```csharp
///
/// Description of config.
///
public record YourPolicyConfig
{
///
/// Description of your property.
///
[ExpressionAllowed]
public required string Property { get; init; }
///
/// Optional property description.
///
[ExpressionAllowed]
public int? OptionalProperty { get; init; }
// Add more properties as needed.
}
```
--------------------------------
### Configure Local NuGet Feed
Source: https://github.com/azure/azure-api-management-policy-toolkit/blob/main/docs/QuickStart.md
XML configuration to add a local package source for the API Management Policy toolkit.
```xml
```
--------------------------------
### LLM Emit Token Metric Policy
Source: https://github.com/azure/azure-api-management-policy-toolkit/blob/main/docs/AvailablePolicies.md
Emits token metrics for LLM usage. Specify the namespace and dimensions for the metrics.
```csharp
c.LlmEmitTokenMetric(new EmitTokenMetricConfig
{
Namespace = "my-namespace",
Dimensions = new MetricDimensionConfig[]
{
new() { Name = "API ID", Value = "@(context.Api.Id)" }
}
});
```
--------------------------------
### Validate Parameters Policy
Source: https://github.com/azure/azure-api-management-policy-toolkit/blob/main/docs/AvailablePolicies.md
Validates query and path parameters. Configure actions for specified and unspecified parameters and specify a variable to store errors.
```csharp
c.ValidateParameters(new ValidateParametersConfig
{
SpecifiedParameterAction = "prevent",
UnspecifiedParameterAction = "prevent",
ErrorsVariableName = "param-errors"
});
```
--------------------------------
### Document API Policy
Source: https://github.com/azure/azure-api-management-policy-toolkit/blob/main/docs/SolutionStructureRecommendation.md
Use the Document attribute to specify the output path for an API policy. This allows for custom naming and placement within a directory tree.
```csharp
[Document("apis/echo-api/policy.xml")]
public class ApiEchoApiPolicy : IDocument
```
--------------------------------
### Set Policy Document Name in C#
Source: https://github.com/azure/azure-api-management-policy-toolkit/blob/main/docs/IntegratePolicySolutionWithApiOps.md
Ensures the policy compiler generates a 'policy.xml' file for each C# policy class by specifying the Document name attribute.
```csharp
[Document("policy.xml")]
```
--------------------------------
### HTTP Proxy Policy
Source: https://github.com/azure/azure-api-management-policy-toolkit/blob/main/docs/AvailablePolicies.md
Configures an HTTP proxy for outgoing requests. Specify the proxy URL, username, and password.
```csharp
c.Proxy(new ProxyConfig
{
Url = "http://proxy.example.com:8080",
Username = "admin",
Password = "secret"
});
```
--------------------------------
### Azure Pipelines for Policy Deployment
Source: https://github.com/azure/azure-api-management-policy-toolkit/blob/main/docs/IntegratePolicySolution.md
This Azure Pipelines definition outlines the steps to build, test, and deploy policy documents to Azure API Management. It uses parameters for subscription, resource group, and service name.
```yaml
parameters:
- name: 'subscription'
displayName: 'Subscription for Azure API Management'
type: string
- name: 'resourceGroup'
displayName: 'Azure API Management resource group'
type: string
- name: 'serviceName'
displayName: 'Azure API Management service name'
type: string
pool:
vmImage: 'ubuntu-latest'
steps:
- task: UseDotNet@2
displayName: 'Setup .NET'
inputs:
version: 8.x
performMultiLevelLookup: true
includePreviewVersions: true
- script: dotnet restore
displayName: 'Restore dependencies'
- script: dotnet build --no-restore
displayName: 'Build with dotnet'
- script: dotnet test --no-build --logger trx --results-directory "TestResults"
displayName: 'Test with dotnet'
- task: PublishTestResults@2
displayName: 'Collect tests results'
inputs:
testRunner: VSTest
testResultsFiles: './TestResults/*.trx'
- script: dotnet tool restore
displayName: 'Restore tools'
- script: dotnet azure-apim-policy-compiler --s .\src\ --o .\infrastructure\
displayName: 'Compile policy documents'
- task: AzureCLI@2
displayName: Azure CLI
inputs:
azureSubscription: ${{ parameters.subscription }}
scriptType: cmd
scriptLocation: inlineScript
inlineScript: |
cd .\infrastructure\
az deployment group create \
--resource-group ${{ parameters.resourceGroup }} \
--template-file .\deployment.bicep \
--parameters servicename=${{ parameters.serviceName }} \
--name deploy-$(Build.BuildNumber)
```
--------------------------------
### Define API Operation Policy
Source: https://github.com/azure/azure-api-management-policy-toolkit/blob/main/docs/QuickStart.md
C# class inheriting from IDocument to define an API operation policy. Includes setting a header in the inbound section.
```csharp
using Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring;
namespace Contoso.Apis.Policies;
[Document]
public class ApiOperationPolicy : IDocument
{
public void Inbound(IInboundContext context)
{
context.Base();
context.SetHeader("X-Hello", "World");
}
}
```
--------------------------------
### Document API Operation Policy
Source: https://github.com/azure/azure-api-management-policy-toolkit/blob/main/docs/SolutionStructureRecommendation.md
Use the Document attribute to specify the output path for an API operation policy. This enables organization of policies within specific operation subdirectories.
```csharp
[Document("apis/echo-api/operations/get/policy.xml")]
public class ApiEchoApiGetPolicy : IDocument
```
--------------------------------
### Azure OpenAI Token Limit Policy
Source: https://github.com/azure/azure-api-management-policy-toolkit/blob/main/docs/AvailablePolicies.md
Enforces a token limit for Azure OpenAI requests. Configure the counter key, tokens per minute, and header for remaining tokens.
```csharp
c.AzureOpenAiTokenLimit(new TokenLimitConfig
{
CounterKey = "my-key",
TokensPerMinute = 10000,
EstimatePromptTokens = true,
RemainingTokensHeaderName = "x-remaining-tokens"
});
```
--------------------------------
### Test Custom Policy Compilation
Source: https://github.com/azure/azure-api-management-policy-toolkit/blob/main/docs/AddPolicyGuide.md
Write unit tests for your custom policy compiler using DataRows. Verify that the compiler correctly handles required and optional parameters, including expressions, across different policy sections.
```csharp
[TestClass]
public class YourPolicyTests : PolicyCompilerTestBase
{
[TestMethod]
[DataRow(
"""
[Document]
public class PolicyDocument : IDocument
{
public void Inbound(IInboundContext context) {
context.YourPolicy(new YourPolicyConfig()
{
Property = "Value"
});
}
}
""",
"""
""")]
public void ShouldCompileYourPolicy(string code, string expectedXml)
{
code.CompileDocument().Should().BeSuccessful().And.DocumentEquivalentTo(expectedXml);
}
}
```
--------------------------------
### Generated Razor Policy Document
Source: https://github.com/azure/azure-api-management-policy-toolkit/blob/main/docs/QuickStart.md
The output of the compilation process is a Razor policy document. This XML file can be directly imported into Azure API Management.
```xml
World
```
--------------------------------
### Define API Operation Policy with Conditional Authentication
Source: https://github.com/azure/azure-api-management-policy-toolkit/blob/main/docs/QuickStart.md
Use this C# code to define a policy that applies different authentication methods based on the request's IP address. It also sets a user ID header for all requests. Requires the Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring namespace.
```csharp
using Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring;
using Microsoft.Azure.ApiManagement.PolicyToolkit.Authoring.Expressions;
namespace Contoso.Apis.Policies;
[Document]
public class ApiOperationPolicy : IDocument
{
public void Inbound(IInboundContext context)
{
if(IsCompanyIP(context.ExpressionContext))
{
context.AuthenticationBasic("{{username}}", "{{password}}");
}
else
{
context.AuthenticationManagedIdentity(new ManagedIdentityAuthenticationConfig
{
Resource = "https://graph.microsoft.com"
});
}
context.SetHeader("X-User-Id", GetUserId(context.ExpressionContext));
}
public static bool IsCompanyIP(IExpressionContext context)
=> context.Request.IpAddress.StartsWith("10.0.0.");
private static string GetUserId(IExpressionContext context)
=> context.User.Id;
}
```
--------------------------------
### Validate Client Certificate Policy
Source: https://github.com/azure/azure-api-management-policy-toolkit/blob/main/docs/AvailablePolicies.md
Validates the client certificate. Configure validation for revocation, trust, and validity periods.
```csharp
c.ValidateClientCertificate(new ValidateClientCertificateConfig
{
ValidateRevocation = true,
ValidateTrust = true,
ValidateNotBefore = true,
ValidateNotAfter = true
});
```
--------------------------------
### Validate Content Policy
Source: https://github.com/azure/azure-api-management-policy-toolkit/blob/main/docs/AvailablePolicies.md
Validates request or response content. Configure actions for unspecified content types and size exceedance, and specify a variable for errors.
```csharp
c.ValidateContent(new ValidateContentConfig
{
UnspecifiedContentTypeAction = "prevent",
MaxSize = 102400,
SizeExceededAction = "prevent",
ErrorsVariableName = "content-errors"
});
```
--------------------------------
### XSL Transform Policy
Source: https://github.com/azure/azure-api-management-policy-toolkit/blob/main/docs/AvailablePolicies.md
Applies an XSL transformation to the request or response body. The XSL stylesheet is provided as a string.
```csharp
c.XslTransform(new XslTransformConfig
{
Xsl = "" +
"" +
"" +
""
});
```
--------------------------------
### Azure OpenAI Semantic Cache Lookup Policy
Source: https://github.com/azure/azure-api-management-policy-toolkit/blob/main/docs/AvailablePolicies.md
Performs a semantic cache lookup for Azure OpenAI requests. Configure embeddings backend, score threshold, and model name.
```csharp
c.AzureOpenAiSemanticCacheLookup(new SemanticCacheLookupConfig
{
EmbeddingsBackendId = "embeddings-backend",
ScoreThreshold = 0.8,
EmbeddingsModelName = "text-embedding-ada-002"
});
```
--------------------------------
### Validate Headers Policy
Source: https://github.com/azure/azure-api-management-policy-toolkit/blob/main/docs/AvailablePolicies.md
Validates request headers against an API schema. Configure actions for specified and unspecified headers, and specify a variable to store errors.
```csharp
c.ValidateHeaders(new ValidateHeadersConfig
{
SpecifiedHeaderAction = "prevent",
UnspecifiedHeaderAction = "ignore",
ErrorsVariableName = "header-errors"
});
```
--------------------------------
### Validate OData Request Policy
Source: https://github.com/azure/azure-api-management-policy-toolkit/blob/main/docs/AvailablePolicies.md
Validates OData requests. Configure the error variable name, default OData version, and maximum size.
```csharp
c.ValidateOdataRequest(new ValidateOdataRequestConfig
{
ErrorVariableName = "odata-errors",
DefaultOdataVersion = "4.0",
MaxSize = 10000
});
```
--------------------------------
### LLM Content Safety Policy
Source: https://github.com/azure/azure-api-management-policy-toolkit/blob/main/docs/AvailablePolicies.md
Performs a content safety check for LLM requests. Specify the backend ID for the content safety service.
```csharp
c.LlmContentSafety(new LlmContentSafetyConfig
{
BackendId = "content-safety-backend"
});
```
--------------------------------
### Generated API Operation Policy XML
Source: https://github.com/azure/azure-api-management-policy-toolkit/blob/main/docs/QuickStart.md
The resulting XML policy document generated from the C# policy definition. This includes conditional inbound policies for authentication and setting a user ID header.
```xml
@(context.User.Id)
```
--------------------------------
### Send Service Bus Message Policy
Source: https://github.com/azure/azure-api-management-policy-toolkit/blob/main/docs/AvailablePolicies.md
Sends a message to an Azure Service Bus queue. Specify the queue name and namespace.
```csharp
c.SendServiceBusMessage(new SendServiceBusMessageConfig
{
QueueName = "my-queue",
Namespace = "my-namespace.servicebus.windows.net"
});
```
--------------------------------
### Publish to Dapr Topic Policy
Source: https://github.com/azure/azure-api-management-policy-toolkit/blob/main/docs/AvailablePolicies.md
Publishes a message to a Dapr topic. Specify the topic name and pub/sub component name.
```csharp
c.PublishToDarp(new PublishToDarpConfig
{
Topic = "my-topic",
PubSubName = "pubsub"
});
```
--------------------------------
### Invoke Dapr Binding Policy
Source: https://github.com/azure/azure-api-management-policy-toolkit/blob/main/docs/AvailablePolicies.md
Invokes a Dapr binding. Specify the binding name, operation, and whether to ignore errors.
```csharp
c.InvokeDarpBinding(new InvokeDarpBindingConfig
{
Name = "my-binding",
Operation = "create",
IgnoreError = true
});
```
--------------------------------
### Validate Status Code Policy
Source: https://github.com/azure/azure-api-management-policy-toolkit/blob/main/docs/AvailablePolicies.md
Validates response status codes. Configure the action for unspecified status codes and specify a variable to store errors.
```csharp
c.ValidateStatusCode(new ValidateStatusCodeConfig
{
UnspecifiedStatusCodeAction = "prevent",
ErrorsVariableName = "statuscode-errors"
});
```
--------------------------------
### Validate Azure AD Token Policy
Source: https://github.com/azure/azure-api-management-policy-toolkit/blob/main/docs/AvailablePolicies.md
Validates an Azure AD token. Specify header name, failure codes/messages, audiences, and required claims.
```csharp
c.ValidateAzureAdToken(new ValidateAzureAdTokenConfig
{
HeaderName = "Authorization",
FailedValidationHttpCode = 401,
FailedValidationErrorMessage = "Unauthorized",
Audiences = new[] { "https://api.example.com" },
RequiredClaims = new ClaimConfig[]
{
new() { Name = "roles", Match = "any", Values = new[] { "admin", "reader" } }
}
});
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.