AzureFunctions.Extensions.Middleware 2.0.1

.NET 5.0 .NET Core 3.1
There is a newer version of this package available.
See the version list below for details.
dotnet add package AzureFunctions.Extensions.Middleware --version 2.0.1
NuGet\Install-Package AzureFunctions.Extensions.Middleware -Version 2.0.1
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="AzureFunctions.Extensions.Middleware" Version="2.0.1" />
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add AzureFunctions.Extensions.Middleware --version 2.0.1
#r "nuget: AzureFunctions.Extensions.Middleware, 2.0.1"
#r directive can be used in F# Interactive, C# scripting and .NET Interactive. Copy this into the interactive tool or source code of the script to reference the package.
// Install AzureFunctions.Extensions.Middleware as a Cake Addin
#addin nuget:?package=AzureFunctions.Extensions.Middleware&version=2.0.1

// Install AzureFunctions.Extensions.Middleware as a Cake Tool
#tool nuget:?package=AzureFunctions.Extensions.Middleware&version=2.0.1


  • Able to add multiple custom middlewares to the pipeline
  • Able to access HTTP context inside the custom middleware
  • Able to inject middlewares in all the triggers available
  • Able to bypass middlewares and return response
  • Handle Crosscutting concerns of the application
    • Logging
    • Exception Handling
    • CORS
    • Performance Monitoring
    • Caching
    • Security
  • Licenced under MIT - 100% free for personal and commercial use

Supported Frameworks

  • NetCoreApp 3.1
  • NET 5.0
  • NET 6.0


Install with Package Manager Console

PM> Install-Package AzureFunctions.Extensions.Middleware


Getting Started

1. Add HttpContextAccessor to service collection

Inorder to access/modify HttpContext within custom middleware we need to add HttpContextAccessor in Startup.cs file.


2. Add custom middlewares to the pipeline

One or more custom middlewares can be added to the execution pipeline using MiddlewareBuilder.

builder.Services.AddTransient<IMiddlewareBuilder, MiddlewareBuilder>((serviceProvider) =>
                var funcBuilder = new MiddlewareBuilder(serviceProvider.GetRequiredService<IHttpContextAccessor>());
                funcBuilder.Use(new ExceptionHandlingMiddleware(new LoggerFactory().CreateLogger(nameof(ExceptionHandlingMiddleware))));
                funcBuilder.UseWhen(ctx => ctx.Request.Path.StartsWithSegments("/api/Authorize"),
                    new AuthorizationMiddleware(new LoggerFactory().CreateLogger(nameof(AuthorizationMiddleware))));
                return funcBuilder;

2.1 Use()

  • Use() middleware takes custom middleware as parameter and will be applied to all the endpoints

2.2 UseWhen()

  • UseWhen() takes Func<HttpContext, bool> and custom middleware as parameters. If the condition is satisfied then middleware will be added to the pipeline of exectuion.

3. IMiddlewareBuilder dependency

We can now add IMiddlewareBuilder as a dependency to our HTTP trigger function class.

        private readonly ILogger<Function1> _logger;
        private readonly IMiddlewareBuilder _middlewareBuilder;

        public Function1(ILogger<Function1> log, IMiddlewareBuilder middlewareBuilder)
            _logger = log;            
            _middlewareBuilder = middlewareBuilder;

4. Execute pipeline

Now we need to bind last middleware for our HttpTrigger method , to do that wrap our existing code inside Functionsmiddleware block "_middlewareBuilder.ExecuteAsync(new FunctionsMiddleware(async (httpContext) ⇒{HTTP trigger code})"

For returning IActionResult use FunctionsMiddleware

return await _middlewareBuilder.ExecuteAsync(new FunctionsMiddleware(async (httpContext) =>
                _logger.LogInformation("C# HTTP trigger function processed a request.");

                string name = httpContext.Request.Query["name"];                

                string requestBody = await new StreamReader(httpContext.Request.Body).ReadToEndAsync();
                dynamic data = JsonConvert.DeserializeObject(requestBody);
                name = name ?? data?.name;

                string responseMessage = string.IsNullOrEmpty(name)
                    ? "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response."
                    : $"Hello, {name}. This HTTP triggered function executed successfully.";

                return new OkObjectResult(responseMessage);

For non-http triggers use TaskMiddleware

       public async Task Run([TimerTrigger("*/10 * * * * *")] TimerInfo myTimer, ILogger log)
         await _middlewareBuilder.ExecuteAsync(new TaskMiddleware(async (httpContext) =>
            log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");
            await Task.FromResult("test");


You can find .NET 6 sample application here . In this example we have registered Exception handling custom middleware to the exectuion order that will handle any unhandled exceptions in the Http Trigger execution.

Special Thanks

Thank you to the following people for their support and contributions!

Leave a ⭐ if this library helped you at handling cross-cutting concerns in serverless architecture.

<a href="" target="_blank"><img src="" alt="Buy Me A Coffee" style="height: 40px !important;width: 145 !important;" ></a>

Website | LinkedIn | Forum | Contribution Guide | Donate | License

© Divakar Kumar

For detailed documentation, please visit the docs.


Divakar Kumar - @Divakar-Kumar -

Project Link:

Product Versions
.NET net5.0 net5.0-windows net6.0 net6.0-android net6.0-ios net6.0-maccatalyst net6.0-macos net6.0-tvos net6.0-windows net7.0 net7.0-android net7.0-ios net7.0-maccatalyst net7.0-macos net7.0-tvos net7.0-windows
.NET Core netcoreapp3.1
Compatible target framework(s)
Additional computed target framework(s)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
3.0.0 2,974 7/20/2022
2.1.0 1,830 6/21/2022
2.0.1 253 6/9/2022
2.0.0 247 6/9/2022
1.0.2 1,116 1/16/2022
1.0.0 259 1/16/2022