Skip to content

Instantly share code, notes, and snippets.

@bryanknox
Last active May 17, 2020 14:29
Show Gist options
  • Save bryanknox/10ef2dfff085e57beae39157216a0eba to your computer and use it in GitHub Desktop.
Save bryanknox/10ef2dfff085e57beae39157216a0eba to your computer and use it in GitHub Desktop.
Examples of Service Bus output binding in an Azure Function. Custom class vs Message.
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.ServiceBus;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Newtonsoft.Json;
using System.Text;
using System.Threading.Tasks;
namespace K0x.Eample.AzureFunctions
{
public static class ServiceBusOutputBindingAzureFunctions
{
[FunctionName("MyFunctionWithCustomClass")]
public static async Task<IActionResult> RunCustomClass(
[HttpTrigger(AuthorizationLevel.Function, "get", Route = null)] HttpRequest req,
[ServiceBus("%MyQueueName%",
Connection = "MyServiceBusConnection")] IAsyncCollector<MyItem> myOutputQueue)
{
var myItem = new MyItem();
// Do stuff.
// . . .
// Add the item to the queue.
await myOutputQueue.AddAsync(myItem);
// Do more stuff.
// . . .
return new OkResult();
}
[FunctionName("MyFunctionWithMessage")]
public static async Task<IActionResult> RunMessage(
[HttpTrigger(AuthorizationLevel.Function, "get", Route = null)] HttpRequest req,
[ServiceBus("%MyQueueName%",
Connection = "MyServiceBusConnection")] IAsyncCollector<Message> myOutputQueue)
{
var myItem = new MyItem();
// Do stuff.
// . . .
// Add the item to the queue, wrapped in a Message.
string json = JsonConvert.SerializeObject(myItem);
Message outputMessage = new Message(Encoding.UTF8.GetBytes(json))
{
ContentType = "application/json",
// Set the MessageId for use in duplicate detection.
MessageId = $"{myItem.TypeId}-{myItem.ItemId}"
};
await myOutputQueue.AddAsync(outputMessage);
// Do more stuff.
// . . .
return new OkResult();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment