Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Dealing CloudEvents with Azure Functions for Azure EventGrid
dotnet add package Azure.Messaging.EventGrid --version 4.0.0-beta.4
az extension add -n eventgrid
endpoint=$(az eventgrid topic show \
-g <resource_group_name> \
-n <eventgrid_topic_name> \
--query "endpoint" -o tsv)
id=$(az eventgrid topic show \
-g <resource_group_name> \
-n <eventgrid_topic_name> \
--query "id" -o tsv)
key=$(az rest \
-m POST \
-u "https://management.azure.com$id/listKeys?api-version=2020-06-01" \
--query "key1" -o tsv)
var topicEndpoint = new Uri("<endpoint>");
var credential = new AzureKeyCredential("<key>");
var publisher = new EventGridPublisherClient(topicEndpoint, credential);
var source = "<source>";
var type = "<type>";
var dataContentType = "application/cloudevents+json";
var data = new MyData() { Hello = "World" };
var @event = new CloudEvent(source, type, data, dataContentType);
var events = new List<CloudEvent>() { @event };
await publisher.SendEventsAsync(events).ConfigureAwait(false);
[FunctionName("HttpTrigger")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "POST", "OPTIONS", Route = "handler")] HttpRequest req,
ILogger log)
{
if (HttpMethods.IsOptions(req.Method))
{
string header = req.Headers["WebHook-Request-Origin"];
req.HttpContext.Response.Headers.Add("Webhook-Allowed-Origin", header);
return new OkResult();
}
...
}
[FunctionName("HttpTrigger")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "POST", "OPTIONS", Route = "handler")] HttpRequest req,
ILogger log)
{
if (HttpMethods.IsOptions(req.Method))
{
...
}
using (var reader = new StreamReader(req.Body))
{
var payload = await reader.ReadToEndAsync().ConfigureAwait(false);
var events = CloudEvent.Parse(payload);
foreach (var @event in events)
{
var timestamp = @event.Time;
var data = await @event.GetDataAsync<MyData>().ConfigureAwait(false);
...
}
}
return new OkResult();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment