Web API As Azure Function - ServiceBusTrigger

In Previous article, We have seen that how to use HttpTrigger along with Web API.

In this article, We will explore How to use ServiceBusTrigger with WebAPI as custom handler. For this I first recommend you will have to see my previous post related to HttpTrigger.

Here also flow is something like following.

image.png

Tools

  • Visual Studio 2022

  • Azure Function Core Tools v4

  • .net 6 SDK

Assumption

  • Basic understanding of Azure Service Bus and creation of subcomponent like topic.

Azure Component Configuration

  • Create topic with name User.

    image.png

  • Create Subscription with name UserTopicProcessorLog for topic user.

    image.png

  • It also required to configure Shared Access Key.

    image.png

Add binding for ServiceBusTrigger

  • Go To C:\CustomHandler

  • Create directory called UserTopicProcessor

  • Inside this directory create function.json with following content.

{
  "bindings": [
    {
      "name": "item",
      "type": "serviceBusTrigger",
      "direction": "in",
      "datatype":"string",
      "topicName": "User",
      "subscriptionName": "UserTopicProcessorLog",
      "connection": "ServiceBusConnection"     
    }
  ]
}

If you are aware of Azure Function then this is something similar to what we provided as an attribute to Function. - connection: This point to environment variable named ServiceBusConnection

  • Go to C:\CustomHandler and add ServiceBusConnection in local.settings.json. Now it will look like following.
{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "UseDevelopmentStorage=true",
    "FUNCTIONS_WORKER_RUNTIME": "custom",
    "ServiceBusConnection": "<<your service bus connection>>"   
  }
}
  • It will look like following now.

  • Let's run function from C:\CustomHandler with command func start. It will display something like following.

  • Upto above point Azure Function trigger configured but we have not add anything at WebAPI.

  • As displayed in diagram above following activity perform.

    • Function hos receive new message on User Topic for specified subscription.

    • It will redirect to Web API with endpoint name is like localhost:<>/<>. In our case this would be like localhost:<>/UserTopicProcessor.

  • Now add Web API code for ServiceBusTrigger. It required post method with specific endpoint mention above. Following is simple that read request and provide response.

app.MapPost("/UserTopicProcessor",async context =>{
     context.Request.EnableBuffering();
     var buffer = new byte[Convert.ToInt32(context.Request.ContentLength)];
     await context.Request.Body.ReadAsync(buffer, 0, buffer.Length);
     Console.WriteLine(System.Text.Encoding.UTF8.GetString(buffer));
     await context.Response.WriteAsJsonAsync( new { Result = "ServiceBus Trigger for User Topic Processor Called"});
});
  • Now let's send our first message to user topic and see. ( Make sure your function is running successful)

  • I am going to send following message. You can use Service Bus Explorer from azure portal to send message. Make sure you choose application/json as content type.

{
    "Message": "Hello World"
}
  • Once you send message and everything is in place. You will see following or something similar.

  • At this stage your service bus trigger is working and processing message. ( You need to write business logic after returning message).

  • Now if you send few different message the you will see message structure and it can be created as class to we get strongly type input.

  • Add following to code.

public class ServiceBusRequest
{
  public Dictionary<string,object> Data {get;set;} = new();
  public Dictionary<string,object> Metadata {get;set;} = new();
}
public class ServiceBusResponse
{
 public object Result {get;set;}
}
  • Refactor map method with following
app.MapPost("/UserTopicProcessor",async (HttpContext context, [FromBody] ServiceBusRequest input) =>
{   
     Console.WriteLine(System.Text.Json.JsonSerializer.Serialize(input));
     await context.Response.WriteAsJsonAsync( new ServiceBusResponse() { Result = "ServiceBus Trigger for User Topic Processor Called"});
});

Summary

Here we have seen that how we can use ServiceBusTrigger with WebAPI. Same way there is possible to use other trigger as well. Regarding input and output binding will try to cover in next couple of article but before that I will explain source code as well as how to deploy to using Azure DevOps CICD pipeline.

Source Code

  • Following link contain entire repo ( HttpTrigger and ServiceBusTrigger) Download

  • Following link contain branch for servicebustrigger. Download

  • It is required to configure ServiceBusConnection in local.settings.json.