Serverless Computing with Azure Functions with ASP.Net Core Web API

Introduction

Azure Functions with an ASP.NET Core Web API, along with a real-world use case, can be a powerful way to demonstrate the capabilities of serverless computing in Azure. In this example, we'll create a serverless Azure Function that processes image uploads to a cloud storage service like Azure Blob Storage. When a user uploads an image through the ASP.NET Core Web API, the Azure Function will be triggered to perform some image processing and then save the processed image back to storage.

Here's a step-by-step guide.

1. Create an ASP.NET Core Web API

Start by creating an ASP.NET Core Web API project.

dotnet new webapi -n ImageProcessingApi

2. Create Azure Functions Project

Next, create an Azure Functions project within the same solution.

dotnet new func -n ImageProcessingFunctions

3. Install Required Packages

In the ImageProcessingApi project, you will need to install Azure.Storage.Blobs package for interacting with Azure Blob Storage.

dotnet add package Azure.Storage.Blobs

4. Implement Image Upload API

In your ImageProcessingApi project, create an API controller that handles image uploads. This controller should accept image uploads, store them in Azure Blob Storage, and trigger an Azure Function for processing. Here's a simplified example.

Author: Sardar Mudassar Ali Khan
[ApiController]
[Route("api/images")]
public class ImageController: ControllerBase
{
    private readonly BlobServiceClient _blobServiceClient;

    public ImageController(IConfiguration configuration)
    {
        _blobServiceClient = new BlobServiceClient(configuration.GetConnectionString("AzureStorage"));
    }

    [HttpPost("upload")]
    public async Task<IActionResult> UploadImage(IFormFile file)
    {
        if (file == null || file.Length == 0)
            return BadRequest("No file uploaded.");

        var containerClient = _blobServiceClient.GetBlobContainerClient("images");
        await containerClient.CreateIfNotExistsAsync();

        var blobClient = containerClient.GetBlobClient(file.FileName);
        await blobClient.UploadAsync(file.OpenReadStream(), true);

        // Trigger the Azure Function to process the image here

        return Ok("Image uploaded successfully.");
    }
}

5. Create the Azure Function

In the ImageProcessingFunctions project, create an Azure Function that will be triggered when an image is uploaded to Blob Storage. Here's an example of an Azure Function that resizes an image.

using System.IO;
using System.Drawing;
using Microsoft.Azure.WebJobs;
using Microsoft.Extensions.Logging;

Author: Sardar Mudassar Ali Khan
public static class ImageProcessingFunction
{
    [FunctionName("ProcessImage")]
    public static void Run(
        [BlobTrigger("images/{name}", Connection = "AzureWebJobsStorage")] Stream imageStream,
        [Blob("processed/{name}", FileAccess.Write)] Stream imageOutput,
        string name,
        ILogger log)
    {
        log.LogInformation($"Processing image: {name}");

        // Perform image processing (e.g., resizing)
        using (var image = new Bitmap(imageStream))
        {
            using (var resizedImage = ResizeImage(image, 800, 600))
            {
                resizedImage.Save(imageOutput, ImageFormat.Jpeg);
            }
        }

        log.LogInformation($"Image processed: {name}");
    }

    private static Bitmap ResizeImage(Bitmap image, int width, int height)
    {
        var newWidth = width;
        var newHeight = height;
        var ratio = Math.Min((float)newWidth / image.Width, (float)newHeight / image.Height);

        newWidth = (int)(image.Width * ratio);
        newHeight = (int)(image.Height * ratio);

        var newImage = new Bitmap(newWidth, newHeight);

        using (var graphics = Graphics.FromImage(newImage))
        {
            graphics.DrawImage(image, 0, 0, newWidth, newHeight);
        }

        return newImage;
    }
}

6. Configure Azure Storage Connection

Ensure that you have configured your Azure Storage connection string in both the ImageProcessingApi and ImageProcessingFunctions projects. You can do this in the local.settings.json file for local development and in Azure Portal for production.

7. Deploy to Azure

Publish your ASP.NET Core Web API and Azure Functions to Azure App Service and Azure Functions App, respectively.

8. Test the Application

You can now test the application by uploading an image through the API. The image will be processed by the Azure Function and stored in the "processed" container in Azure Blob Storage.

This example demonstrates how to combine an ASP.NET Core Web API with Azure Functions to perform serverless image processing, a real-world use case that benefits from the scalability and cost-effectiveness of serverless computing in Azure. You can expand on this example by adding more image processing capabilities or integrating with other Azure services as needed for your specific use case.

Conclusion

In this example, we've demonstrated the integration of Azure Functions with an ASP.NET Core Web API to create a serverless image processing application. This real-world use case showcases the power and flexibility of serverless computing in Azure. Here are some key takeaways:

  1. Serverless Computing Benefits: Serverless computing allows you to build scalable and cost-effective solutions. Azure Functions automatically scale based on demand, reducing the need for manual infrastructure management.
  2. Integration with Azure Services: Azure Functions seamlessly integrate with various Azure services, such as Azure Blob Storage, enabling you to create robust and efficient solutions that leverage the entire Azure ecosystem.
  3. ASP.NET Core Web API: ASP.NET Core provides a reliable and versatile platform for building RESTful APIs. Combining it with Azure Functions allows you to handle both synchronous and asynchronous operations in your application.
  4. Real-World Use Case: Image processing is a common real-world use case for serverless computing. You can adapt this example for other scenarios, such as data processing, file conversions, or any task that can be triggered asynchronously.
  5. Azure Cloud Ecosystem: Azure offers a wide range of services beyond Azure Functions and Blob Storage. Depending on your application's requirements, you can explore additional Azure services like Azure Logic Apps, Azure Cognitive Services, Azure Data Lake, or Azure SQL Database.
  6. Deployment and Scalability: Azure simplifies deployment and scaling. You can deploy your applications to Azure App Service and Azure Functions, and Azure's auto-scaling capabilities ensure that your application can handle varying workloads.
  7. Monitoring and Debugging: Azure provides tools like Azure Application Insights for monitoring, logging, and diagnosing issues in your applications, making it easier to maintain and troubleshoot your serverless solution.
  8. Security and Configuration: Ensure that you follow best practices for securing your applications and configure access controls, authentication, and authorization as needed. Azure offers robust security options to protect your serverless applications and data.

Remember that this example serves as a starting point, and you can extend and customize it to meet the specific requirements of your project. Serverless computing in Azure provides a powerful and flexible platform for building scalable and cost-efficient applications, making it an excellent choice for a wide range of scenarios.


Similar Articles